如何使用LINQ检查特定XML节点是否存在

时间:2014-01-16 22:50:21

标签: c# xml linq-to-xml

由于"<dnsServer>""<dnsServers>"标记不存在,我收到错误消息。我试图检查它是否为null但我的代码不起作用。我收到错误:

  

{“对象引用未设置为对象的实例。”}

以下是代码:

var networkElement = doc.Root
                        .Element("networkAdapters")
                        .Elements("networkAdapter")
                        .First(a => (string)a.Attribute("id") == networkAdapter.networkAdapterId.ToString());

var dnsServers = networkElement.Element("dnsServers")
                               .Elements("dnsServer") == null ? null : networkElement.Element("dnsServers").Elements("dnsServer");

和XML示例:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<server id="454a8a22-8e9e-4023-9a8e-c8a4e0f259b3" productName="Manifest" created="2014-01-16T22:07:28" name="SERVER001">
  <networkAdapters>
    <networkAdapter id="bfcbda99-719c-4b0c-b7b2-b9167350c982" busLocation="0-N2" permanentMacAddress="00144FE5448E" physicalAdapter="True" ipEnabled="False">
      <defaultGateways />
      <ipAddresses />
    </networkAdapter>
    <networkAdapter id="73606723-fd91-40df-96dd-0bff7851cea6" ipEnabled="True">
      <defaultGateways>
        <defaultGateway address="99.15.210.1" index="0" />
      </defaultGateways>
      <ipAddresses>
        <ipAddress address="99.15.210.7" subnetMask="255.255.255.224" index="0" />
      </ipAddresses>
    </networkAdapter>
    <networkAdapter id="6520a041-2cf3-40b1-b123-1eb13f704442" busLocation="0-N3" permanentMacAddress="00144FE5448F" physicalAdapter="True" ipEnabled="False">
      <defaultGateways />
      <ipAddresses />
    </networkAdapter>
  </networkAdapters>
</server>

谢谢

1 个答案:

答案 0 :(得分:0)

请尝试以下操作:

var servers = networkElement.Element("dnsServers") ?? new XElement("dnsServers");
var dnsServers = servers.Elements("dnsServer");

当文档中没有<dnsServers>时,如果您的Elements("dnsServer")查询无异常地工作,它将创建空var dnsServers = (networkElement.Element("dnsServers") ?? new XElement("dnsServers")).Elements("dnsServer");

你可以做到这一点:

{{1}}