I have a StringBuilder with the contents of an XML file. Inside the XML file is a root tag called <root>
and contains multiple <node>
tags.
I'd like to parse through the XML to read values of tags within in s, but not sure how to do it.
Will I have to use some C# XML data type for this?
Thanks in advance
StringBuilder sb = new StringBuilder (xml);
TextReader textReader = new StringReader (sb.ToString ());
XDocument xmlDocument = XDocument.Load (textReader);
var nodeValueList = from node in xmlDocument.Descendants ("node")
select node.Value;
You should use classes available in either System.Xml
or System.Xml.Linq
to parse XML.
XDocument
is part of the LINQ extensions for XML and is particularly easy to use if you need to parse through an arbitrary structure. I would suggest using it rather than XmlDocument
(unless you have legacy code or are not on .NET 3.5).
Creating an XDocument
from a StringBuilder
is straightforward:
var doc = XDocument.Parse( stringBuilder.ToString() );
From here, you can use FirstNode
, Descendents()
, and the many other properties and methods available to walk and examine the XML structure. And since XDocument
is designed to work well with LINQ, you can also write queries like:
var someData = from node in doc.Descendants ("yourNodeType")
select node.Value; // etc..
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