Better way to convert a string to XmlNode in C#

C#Xml

C# Problem Overview


I wanted to convert a string (which obviously is an xml) to an XmlNode in C#.While searching the net I got this code.I would like to know whether this is a good way to convert a string to XmlNode? I have to preform this conversion within a loop, so does it cause any performace issues?

        XmlTextReader textReader = new XmlTextReader(new StringReader(xmlContent));
        XmlDocument myXmlDocument = new XmlDocument();
        XmlNode newNode = myXmlDocument.ReadNode(textReader);

Please reply,

Thanks
Alex

C# Solutions


Solution 1 - C#

should be straight-forward:

        string xmlContent = "<foo></foo>";
        XmlDocument doc = new XmlDocument();
        doc.LoadXml(xmlContent);
        XmlNode newNode = doc.DocumentElement;

or with LINQ if that's an option:

        XElement newNode  = XDocument.Parse(xmlContent).Root;

Solution 2 - C#

The accepted answer works only for single element. XmlNode can have multiple elements like string xmlContent = "<foo></foo><bar></bar>"; (Exception: "There are multiple root elements");

To load multiple elements use this:

string xmlContent = "<foo></foo><bar></bar>";
XmlDocument doc = new XmlDocument();
doc.LoadXml("<singleroot>"+xmlContent+"</singleroot>");
XmlNode newNode = SelectSingleNode("/singleroot");

Solution 3 - C#

XmlDocument Doc = new XmlDocument();
Doc.LoadXml(xml);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionwizzardzView Question on Stackoverflow
Solution 1 - C#BrokenGlassView Answer on Stackoverflow
Solution 2 - C#Evžen ČernýView Answer on Stackoverflow
Solution 3 - C#smr fakhriView Answer on Stackoverflow