C# 将 XML 文件转换为字符串类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15895670/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 18:19:41  来源:igfitidea点击:

Converting an XML file to string type

c#xml

提问by Pedram

How can we write an XML file into a string variable? Here is the code I have,the variable content is supposed to return an XML string:

我们如何将 XML 文件写入字符串变量?这是我的代码,变量内容应该返回一个 XML 字符串:

    public string GetValues2()
    {
        string content = "";
        XmlTextWriter textWriter = new XmlTextWriter(content, null);
        textWriter.WriteStartElement("Student");
        textWriter.WriteStartElement("r", "RECORD", "urn:record");
        textWriter.WriteStartElement("Name", "");
        textWriter.WriteString("Student");
        textWriter.WriteEndElement();
        textWriter.Close();

        return contents;

    }

采纳答案by Sachin

Something like this

像这样的东西

string xmlString =  System.IO.File.ReadAllText(fileName);

Here is good answer to create XmlDocumentXDocument or XMLDocument

这是创建XDocument 或 XMLDocument 的好答案XmlDocument

回答by Chandru velan

HI Pedram You can Try the below code

嗨 Pedram 你可以试试下面的代码

XmlDocument doc = new XmlDocument();

doc.LoadXml("yourXMLPath");
StringWriter sw = new StringWriter();
XmlTextWriter tx = new XmlTextWriter(sw);
doc.WriteTo(tx);
sw.ToString();

回答by Sandy

Try this-

尝试这个-

XmlDocument doc = new XmlDocument();
doc.LoadXml(your text string);

StringBuilder sb = new StringBuilder();
foreach (XmlNode node in doc.DocumentElement.ChildNodes)
{
    sb.Append(char.ToUpper(node.Name[0]));
    sb.Append(node.Name.Substring(1));
    sb.Append(' ');
    sb.AppendLine(node.InnerText);
}
return sb;

have a look on this too-

也看看这个——

    StringWriter sw = new StringWriter();
    XmlTextWriter tx = new XmlTextWriter(sw);
    myxml.WriteTo(tx);

    string str = sw.ToString();// 
    return str;

and if you really want to create a new XmlDocument then do this

如果你真的想创建一个新的 XmlDocument 然后这样做

XmlDocument newxmlDoc= myxml