【问题标题】:Verify node exists before getting its value在获取其值之前验证节点是否存在
【发布时间】:2012-10-02 21:11:46
【问题描述】:

我使用 C# 将 xml 值存储在一个字符串中。

string abcd="<xstructure><a>
   <a1>1</a1>
   <a2>2</a2>
   <a3>3</a3>
</a>

<b>4</b>
</xstructure>";

我从字符串中检索了 xml 值,例如,

 var xElem = XElement.Parse(abcd);
 string b= xElem.Element("b").Value;

工作正常。如何检查 XML 结构中是否存在 Xml 节点?如果我尝试从结构中获取 C 值,则 XML 结构中不存在 C 值。所以我需要在我尝试获取 C 值之前检查 c 值是否可用。我该怎么做?

【问题讨论】:

  • 无效的xml,必须只有一个根节点。
  • @ChuckSavage 现在检查该结构

标签: c# xml xml-parsing xml-serialization


【解决方案1】:

试试,

XElement c = xElem.Element("c");
if(null != c)
{
   // do something with c because it exists, like...
   string cValue = c.Value;
}

【讨论】:

    猜你喜欢
    • 2012-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-12
    • 2021-06-03
    • 2020-09-12
    • 1970-01-01
    相关资源
    最近更新 更多