C#中指定块内的XmlDocument GetElementsByTagName

XmlDocument GetElementsByTagName within a specified block in C#

我有一个 xml 文件,目前我正在按标签名称获取元素。我想要实现的是指定要使用哪个块,例如书店或商店。感谢您的帮助和建议。

XML:

<VariablesSpecs name="Data01">
  <bookstore>
    <book genre='novel' ISBN='10-861003-324'>
      <title>The Handmaid's Tale</title>
      <price>19.95</price>
    </book>
  </bookstore>
  <shop>
    <book genre='novel' ISBN='10-861003-324'>
      <title>The Handmaid's Tale</title>
      <price>19.95</price>
    </book>
  </shop>
</VariablesSpecs>

代码:

var doc = new XmlDocument();
doc.Load("data.xml");

var bookNodes = doc.GetElementsByTagName("book");
foreach (var bookNode in bookNodes)
{
    // Collect data.
}

您没有使用 Linq 来 XML:

var doc = XDocument.Load("data.xml");

var bookNodes = doc.Descendants("book").Where(b=> b.Parent.Name == "shop");

使用常规 System.Xml:

var doc = new XmlDocument();
doc.Load("data.xml");
var bookNodes = doc.SelectNodes(@"//bookstore/book");
foreach (XmlNode item in bookNodes)
{
    string title = item.SelectSingleNode("./title").InnerText;
    string price = item.SelectSingleNode("./price").InnerText;
    Console.WriteLine("title {0} price: {1}",title,price); //just for demo
}

您可以使用 XDocument class 以下方式:

XDocument Doc = XDocument.Load("data.xml");
// getting child elements of bookstore
var result = from d in Doc.Descendants("bookstore").Descendants("book")
             select new 
             {
               Name = d.Element("title").Value,
               Price = d.Element("price").Value
             };

// getting child elements of shop
var result = from d in Doc.Descendants("shop").Descendants("book")
             select new 
             {
               Name = d.Element("title").Value,
               Price = d.Element("price").Value
             };