简体   繁体   English

如何检查XML中是否存在元素

[英]How to check an element exist in XML

<library>
    <book>
      <id>1</id>
      <name>abc</name>
         <read>
          <data>yes</data>
          <num>20</num>
        </read>
    </book>
    <book>
      <id>20</id>
      <name>xyz</name>
         <read>
          <data>yes</data>
        </read>
    </book>
    <book>
      <id>30</id>
      <name>ddd</name>
    </book>
</library>

From this I am reading the <book> node with element <id> value = 20 using below code 从这里我正在使用以下代码读取元素<id>值= 20的<book>节点

XElement root = XElement.Load("e_test.xml")
XElement book = root.Elements("book")
                    .Where(x => (int) x.Element("id") == 20)
                    .SingleOrDefault();
if (book == null)
{
    // No book with that ID
}



if(book.Element("read").Element("num") != null) //check the node exist
{
    int num = (int) book.Element("read").Element("num");
}

Here the if condition is not working correctly. 在这里,if条件无法正常运行。 It is passing the condition and get inside and giving null exception. 它正在传递条件并进入内部并给出null异常。 Is this the right way to check the same? 这是正确的检查方法吗?

I am using .NET FRAMEWORK 4.0 我正在使用.NET FRAMEWORK 4.0

You need to check for null for each of Elements calls: 您需要为每个Elements调用检查是否为null

if(book != null && book.Element("read") != null && book.Element("read").Element("num") != null) //check the node exist

in C# 6 you can use ?. 在C#6中,您可以使用?. operator to make it feel nicer: 运算符,使其感觉更好:

if(book?.Element("read")?.Element("num") != null) //check the node exist

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

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