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
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/…
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;
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With