Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to convert a string to XmlNode in C#

Tags:

c#

xml


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

like image 841
wizzardz Avatar asked Nov 09 '10 03:11

wizzardz


People also ask

How do you convert XElement to XmlNode?

Here is converting from string to XElement to XmlNode and back to XElement. ToString() on XElement is similar to OuterXml on XmlNode. You could also use ImportNode msdn.microsoft.com/en-us/library/…


2 Answers

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;
like image 158
BrokenGlass Avatar answered Oct 20 '22 16:10

BrokenGlass


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");
like image 32
Evžen Černý Avatar answered Oct 20 '22 14:10

Evžen Černý