如何检查 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>
我正在使用下面的代码
读取元素<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");
}
这里的 if 条件没有正常工作。它正在传递条件并进入内部并给出空异常。这是正确的检查方法吗?
我正在使用 .NET FRAMEWORK 4.0
您需要为每个 Elements
个调用检查 null
:
if(book != null && book.Element("read") != null && book.Element("read").Element("num") != null) //check the node exist
在 C# 6 中,您可以使用 ?.
运算符使其感觉更好:
if(book?.Element("read")?.Element("num") != null) //check the node exist
<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>
我正在使用下面的代码
读取元素<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");
}
这里的 if 条件没有正常工作。它正在传递条件并进入内部并给出空异常。这是正确的检查方法吗?
我正在使用 .NET FRAMEWORK 4.0
您需要为每个 Elements
个调用检查 null
:
if(book != null && book.Element("read") != null && book.Element("read").Element("num") != null) //check the node exist
在 C# 6 中,您可以使用 ?.
运算符使其感觉更好:
if(book?.Element("read")?.Element("num") != null) //check the node exist