C# 如何从xml节点列表中选择单个节点?
我在C中有一个XmlDocument对象,其结构如下: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>
<?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
}
}