Quantum_Kernel
Quantum_Kernel

Reputation: 333

Get text from all instances of XML element using C#

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

Answers (2)

Jake Reece
Jake Reece

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.

  • The Descendents method will get all children of the XML document, which takes care of your unknown XML structure.
  • The 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

Gaurang Dave
Gaurang Dave

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

Related Questions