【问题标题】:How do I select a single node from an xml node list?如何从 xml 节点列表中选择单个节点?
【发布时间】:2016-12-12 06:39:56
【问题描述】:

我在 C# 中有一个 XmlDocument 对象,其结构如下:

<?xml version="1.0"?>
<catalog>
   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications 
      with XML.</description>
   </book>
   <book id="bk102">
      <author>Ralls, Kim</author>
      <title>Midnight Rain</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2000-12-16</publish_date>
      <description>A former architect battles corporate zombies, 
      an evil sorceress, and her own childhood to become queen 
      of the world.</description>
   </book>
</catalog>

我正在创建一本书 NodeList 并循环分配给作者字符串数组。当我尝试时

XmlNodeList xnl = xmlDocument.SelectNodes("//catalog/book");
for (int i = 0; i < xnl.Count; i++)
{
    authors[i] = xnl[i].SelectSingleNode("//author").InnerText;
}

我得到一个空引用异常。为什么 SelectSingleNode 的结果应该为 null?

【问题讨论】:

  • 我认为作者的双斜杠是不必要的,不是吗?除此之外,它看起来是合法的,除非authors 给你例外......
  • @Mitch 你是对的。问题是未定义作者数组的大小。
  • 发生在我们所有人身上。

标签: c# .net xml xpath


【解决方案1】:

尝试以下方法之一

for (int i = 0; i < xnl.Count; i++)
{
    authors[i] = xnl[i].SelectSingleNode("//author").value;
}

for (int i = 0; i < xnl.Count; i++)
{
    authors[i] = xnl[i].Attributes["author"].value;
}

【讨论】:

  • 它甚至不会编译。
【解决方案2】:

试试这个,

var all_elements = xmldoc.DocumentElement.SelectNodes("//catalog/book/author");

        foreach(XmlNode sub_elements in all_elements)
        {
            if(sub_elements.InnerText != "")
            {
                string answer = sub_elements.InnerText;
            }
            else
            {
                //null text
            }
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-01
    • 2020-08-28
    • 2021-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多