简体   繁体   中英

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

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. It is passing the condition and get inside and giving null exception. Is this the right way to check the same?

I am using .NET FRAMEWORK 4.0

You need to check for null for each of Elements calls:

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

in C# 6 you can use ?. operator to make it feel nicer:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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