简体   繁体   中英

.NET LINQ2XML parsing XML and getting all nodes with specifc name

I'm trying to migrate into using Linq2XML after using some other ways of parsing XML like following:

 string xml = "//some xml file here";
 XmlDocument doc = new XmlDocument();
 doc.LoadXml(xml);
 for (int i = 0; i < doc.GetElementsByTagName("Title").Count; i++)
 {
  // get all elements values that have this tag name
 }

I would like to now translate this into LINQ2XML and to basically write a query against this test XML file..

Can someone help me out? Would I have to store it into an array of Titles or something like that ?

You can use XContainer.Descendants(XName) (or XElement.DescendantsAndSelf(XName) on the root element):

var doc = XDocument.Parse(xml);
foreach (var element in doc.Descendants("Title"))
{
    // element is an element with the name "Title" -- process it however
    // you want.
}

Note that, if you are modifying the document by adding or removing elements inside the foreach loop, you will need to snapshot the list like so:

foreach (var element in doc.Descendants("Title").ToList())
{
    // element is an element with the name "Title" -- process it however
    // you want.
}

Finally, if you want to find elements with just a specific local name and ignore namespace, you can do:

foreach (var element in doc.Descendants().Where(e => e.Name.LocalName == "Title"))
{
    // element is an element with the local name "Title" -- process it however
    // you want.
}

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