如何使用Linq to XML检查XML子元素是否存在

18

如何使用 Linq to Xml 来检查 IncomingConfig 元素是否存在?

<?xml version="1.0" encoding="utf-8"?>
<settings>
  <IncomingConfig>
    <ip>10.100.101.18</ip>
    <port>5060</port>
  </IncomingConfig>
  <Device>
    <username>tarek</username>
    <AgentName>tarek</AgentName>
    <password>ffff</password>
  </Device>
  <Device>
    <username>adf</username>
    <AgentName>adf</AgentName>
    <password>fadsf</password>
  </Device>
</settings>
1个回答

29
bool b = xdocument.Descendants("IncomingConfig").Any();

9
如果只想检查IncomingConfig是否是根节点的子节点(而不是任何其他节点的后代),可以使用xdocument.Root.Element("IncomingConfig") != null - Steve Guidi
@L.B 对不起,我把命名空间误认为是一个元素了。 - Anirudha
更正 - "Element" 应该是复数形式,所以应为 xdocument.Root.Elements("IncomingConfig") != null。谢谢! - Leo Gurdian

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接