简体   繁体   English

检查Xml标签是否存在于xpath中。

[英]Check Xml tag exist in xpath.

I am trying to get value from Xml file using xpath. 我正在尝试使用xpath从Xml文件中获取价值。 Here is my code: 这是我的代码:

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

This is working fine when Quote Xml node exist in XML file and return value in between Quote tags. 当XML文件中存在Quote Xml节点并在Quote标签之间返回值时,此方法工作正常。 However Quote xml tag not exist in the XMl file it generates and exception. 但是,Quote xml标记在它生成的XMl文件中不存在并且异常。

Object reference not set to an instance of an object.

I have tried to check NULL as below: 我试图检查NULL如下:

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

and

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

However it doesn't avoid the execution when null. 但是,如果为null,则无法避免执行。

Please help me to avoid execution when Xml tag not exist. 当Xml标签不存在时,请帮助我避免执行。

Maybe the boolean() XPATH function helps here: 也许boolean() XPATH函数在这里有帮助:

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

If element Quote exists, boolean(//*[name()='Quote']) should return true, otherwise false. 如果存在元素Quote,则boolean(//*[name()='Quote'])应该返回true,否则返回false。

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

Try 尝试

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM