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

前端 未结 10 1135
感动是毒
感动是毒 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:28

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

    string theString = "blah";
    XDocument doc = XDocument.Parse(theString);
    

    You can also create a fragment with:

    string theString = "blah";
    XElement element = XElement.Parse(theString);
    

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

    string theString = "blah";
    //creates blah
    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.

提交回复
热议问题