简体   繁体   中英

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#?

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.
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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM