2012-12-11 39 views
1

我想從xml文件中使用xpath獲取值。這裏是我的代碼:檢查xml標籤是否存在於xpath中。

XElement docQuote = XElement.Parse(Financial); 
string result= docQuote.XPathSelectElement("//ns:Quote",nsmgr).ToString(SaveOptions.DisableFormatting); 

Quote XML節點XML文件,返回值Quote標籤之間存在這是工作的罰款。但是Quote Xml標籤不存在於它生成的XMl文件和異常中。

Object reference not set to an instance of an object. 

我試圖檢查如下NULL:

if(docQuote.XPathSelectElement("//ns:Quote",nsmgr) != null

if(docQuote.XPathSelectElement("//ns:Quote",nsmgr) != null).value != null) 

但是它不會避免執行時無效。

當Xml標籤不存在時,請幫助我避免執行。

+0

你確定你的nsmgr對象不是null嗎? –

回答

-1

嘗試

XElement docQuote = XElement.Parse(Financial); 
    if(docQuote != null && docQuote.XPathSelectElement("//ns:Quote",nsmgr) != null) 
    { 
    string result= docQuote.XPathSelectElement("//ns:Quote",nsmgr).ToString(SaveOptions.DisableFormatting); 
    } 
+0

由於docQuote不爲空,所以這不起作用。而當你要執行下半部分的檢查時,它會引發異常。 – devan

+0

你能顯示完整的代碼嗎? nsmgr財務對象e.t.c 可能存在申報 檢查http://stackoverflow.com/questions/5819305/xpathselectelement-always-returns-null 附:錯誤 [投票-1 :)] –

2

也許boolean() XPATH功能有助於在這裏:​​

boolean(//*[name()='Quote']) 

如果元素報價存在,boolean(//*[name()='Quote'])應返回true,否則爲false。

XElement docQuote = XElement.Parse(Financial); 
string result= docQuote.XPathSelectElement("boolean(//*[name()='Quote'])",nsmgr).ToString(SaveOptions.DisableFormatting);