【问题标题】:XmlDocument GetElementsByTagName within a specified block in C#C# 中指定块内的 XmlDocument GetElementsByTagName
【发布时间】:2015-02-18 10:08:58
【问题描述】:

我有一个 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.
}

【问题讨论】:

  • 请以文本形式包含 XML。

标签: c# xml linq-to-xml xmldocument


【解决方案1】:

您没有使用 Linq to 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
}

【讨论】:

  • 我知道,但如果有 LinqToXml 的 smt 也很好。但是,没有 linq 的 smt 呢?
  • 如何使用 foreach 循环实现?
  • @doro 如果您还需要属性: string isbn = item.Attributes.GetNamedItem("ISBN").Value; string isbnusingxpath = item.SelectSingleNode("./@ISBN").InnerText;
【解决方案2】:

您可以通过以下方式使用XDocument类:

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
             };

【讨论】:

  • 谢谢,不用 linq 使用 XmlDocument 吗?
  • 我一直更喜欢使用XDocument,因为它很容易遍历文档
猜你喜欢
  • 2020-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-19
  • 2010-10-24
相关资源
最近更新 更多