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

时间:2016-12-12 06:39:57

标签: 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>
      <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?

2 个答案:

答案 0 :(得分:1)

尝试以下其中一项

customheader.phtml

OR

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

答案 1 :(得分:0)

试试这个,

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