2012-08-31 25 views
1

考慮下面的XML:XML的SelectSingleNode其中兄弟= '東西'

<SomeRoot> 
    <SomeElement> 
    <SomeThing>25</SomeThing> 
    <SomeOther>Cat</SomeOther> 
    </SomeElement> 
    <SomeElement> 
    <SomeThing>46</SomeThing> 
    <SomeOther>Dog</SomeOther> 
    </SomeElement> 
    <SomeElement> 
    <SomeThing>83</SomeThing> 
    <SomeOther>Bat</SomeOther> 
    </SomeElement> 
    <SomethingElse>Unrelated to the SomeElements above</SomethingElse> 
</SomeRoot> 

我想select SomeThing where SomeOther = 'Cat'。以下C#代碼引發空引用異常:

xmlDoc = new XmlDocument(); 
this.path = path; 
// Path is passed elsewhere 

Console.WriteLine(xmlDoc.SelectSingleNode("/SomeRoot/SomeElement/SomeThing[../SomeOther='Cat']").InnerText); 

這裏使用的正確XPath語法是什麼?

回答

2

你缺少負載

var xmlDoc = new XmlDocument(); 
xmlDoc.Load(path); 
Console.WriteLine(xmlDoc.SelectSingleNode("/SomeRoot/SomeElement/SomeThing[../SomeOther='Cat']").InnerText); 
+1

你可以在這裏確認你的XPATH:http://xpath.online-toolz.com/tools/xpath-editor.php – nzjoel

+0

原來我從CMD運行程序時沒有改過目錄到正確的目錄。它試圖加載./SomeXML.xml,而工作目錄錯誤。這個答案幫我解決了這個問題......謝謝! –

1

以下是我所做的工作;

XmlDocument xDoc = new XmlDocument(); 
xDoc.LoadXml(@"<SomeRoot><SomeElement><SomeThing>25</SomeThing><SomeOther>Cat</SomeOther></SomeElement></SomeRoot>"); 

var x = xDoc.SelectSingleNode("/SomeRoot/SomeElement/SomeThing[../SomeOther= 'Cat']").InnerText; 
+0

謝謝,這有助於調試! –

1

可避免使用任何反向軸

/*/SomeElement[SomeOther='Cat']/SomeThing 
+0

謝謝,這很有用! –

+0

@DannyBeckett,不客氣。在XPath中,如果XPath表達式不包含後向軸,如「..」(它是「parent :: node()」的縮寫),則認爲它是DRY(或乾燥)。上導航和下導航的表達式比導航僅向下的表達式更難理解(通常評估效率較低)。 –