Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何从xml节点列表中选择单个节点?_C#_.net_Xml_Xpath - Fatal编程技术网

C# 如何从xml节点列表中选择单个节点?

C# 如何从xml节点列表中选择单个节点?,c#,.net,xml,xpath,C#,.net,Xml,Xpath,我在C中有一个XmlDocument对象,其结构如下: <?xml version="1.0"?> <catalog> <book id="bk101"> <author>Gambardella, Matthew</author> <title>XML Developer's Guide</title> <genre>Computer</genre>

我在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>
我正在创建一个book节点列表,并循环分配给authors字符串数组。当我尝试

XmlNodeList xnl = xmlDocument.SelectNodes("//catalog/book");
for (int i = 0; i < xnl.Count; i++)
{
    authors[i] = xnl[i].SelectSingleNode("//author").InnerText;
}
我得到一个空引用异常。为什么SelectSingleNode的结果应为空?

请尝试以下方法之一

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

试试这个

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

我认为作者的双斜杠是不必要的,不是吗?除此之外,它看起来是合法的,除非作者给了你例外…@Mitch你是对的。问题是authors数组的大小没有定义。这在我们所有人身上都会发生。它甚至不会编译。
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
            }
        }