2016-12-12 87 views
1

我在C#XmlDocument對象具有這樣的結構:如何從xml節點列表中選擇單個節點?

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

我創建了一本書節點列表,並通過分配給一個作家字符串數組循環。當我嘗試

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

我得到一個空引用異常。爲什麼SelectSingleNode的結果應爲null?

+0

我認爲作者的雙斜槓是不必要的,不是嗎?除此之外它看起來合法,除非'作者'給你例外... – Mitch

+0

@Mitch你是對的。問題是作者數組的大小沒有定義。 –

+0

適用於我們所有人。 – Mitch

回答

1

請嘗試以下

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

OR

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

它甚至不會編譯。 –

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