In C#, what is the best method to format a string as XML?

前端 未结 10 1082
感动是毒
感动是毒 2021-01-01 08:32

I am creating a lightweight editor in C# and would like to know the best method for converting a string into a nicely formatted XML string. I would hope that there\'s a pub

相关标签:
10条回答
  • 2021-01-01 09:19
    string unformattedXml = "<?xml version=\"1.0\"?><book><author>Lewis, C.S.</author><title>The Four Loves</title></book>";
    string formattedXml = XElement.Parse(unformattedXml).ToString();
    Console.WriteLine(formattedXml);
    

    Output:

    <book>
      <author>Lewis, C.S.</author>
      <title>The Four Loves</title>
    </book>
    

    The Xml Declaration isn't output by ToString(), but it is by Save() ...

      XElement.Parse(unformattedXml).Save(@"C:\doc.xml");
      Console.WriteLine(File.ReadAllText(@"C:\doc.xml"));
    

    Output:

    <?xml version="1.0" encoding="utf-8"?>
    <book>
      <author>Lewis, C.S.</author>
      <title>The Four Loves</title>
    </book>
    
    0 讨论(0)
  • 2021-01-01 09:20

    It sounds like you want to load the XML into an XmlTextWriter objects and set the Formatting and Indentation properties:

    writer.Formatting = Formatting.Indented;
    writer.Indentation = 1;
    writer.IndentChar = '\t';
    
    0 讨论(0)
  • 2021-01-01 09:21

    If you just need to escape XML characters the following might be useful:

    string myText = "This & that > <> &lt;";
    myText = System.Security.SecurityElement.Escape(myText);
    
    0 讨论(0)
  • 2021-01-01 09:28

    Using the new System.Xml.Linq namespace (System.Xml.Linq Assembly) you can use the following:

    string theString = "<nodeName>blah</nodeName>";
    XDocument doc = XDocument.Parse(theString);
    

    You can also create a fragment with:

    string theString = "<nodeName>blah</nodeName>";
    XElement element = XElement.Parse(theString);
    

    If the string is not yet XML, you can do something like this:

    string theString = "blah";
    //creates <nodeName>blah</nodeName>
    XElement element = new XElement(XName.Get("nodeName"), theString); 
    

    Something to note in this last example is that XElement will XML Encode the provided string.

    I highly recommend the new XLINQ classes. They are lighter weight, and easier to user that most of the existing XmlDocument-related types.

    0 讨论(0)
提交回复
热议问题