Reputation: 333
I need to parse XML files where I can't predict the structure. I need to fill a string array with the inner text from every instance of the below tag no matter where they occur in the tree.
<SpecialCode>ABCD1234</SpecialCode>
Is there a simple way to accomplish this using c#?
Upvotes: 1
Views: 2848
Reputation: 1168
Solution
If your XML is a string:
XDocument doc = XDocument.Parse("<SpecialCode>ABCD1234</SpecialCode>");
string[] specialCodes = doc.Descendants("SpecialCode").Select(n => n.Value).ToArray();
If your XML is a file:
XDocument doc = XDocument.Load("specialCodes.xml");
string[] specialCodes = doc.Descendants("SpecialCode").Select(n => n.Value).ToArray();
Explanation
XDocument
is a handy class that allows for easy XML parsing. You'll need to add a reference to the System.Xml.Linq
assembly to your project in order to use it.
Descendents
method will get all children of the XML document, which takes care of your unknown XML structure.Select
method is a LINQ method and allows us to select a property from each node--in this case, Value
.ToArray
converts the IEnumerable result from Select()
to your desired result.Upvotes: 3
Reputation: 4046
XmlDocument doc = new XmlDocument();
doc.Load(FILENAME);
// IN CASE OF STRING, USE FOLLOWING
//doc.LoadXml(XAML_STRING);
XmlNodeList list = doc.DocumentElement.SelectNodes("//SpecialCode");
// prefic will fetch all the SpecialCode
tags from xml.
Upvotes: 0