Better way to convert a string to XmlNode in C#
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
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");