检查XML节点的存在与否? [英] Check xml node is exist or not?
问题描述
我要检查给定的节点是存在或不*。xml的
文件。
我尝试:
I want to check given node is exist or not in *.xml
file.
I try:
string language = node.SelectSingleNode("language") != null ? (node.SelectSingleNode("language").Value == "en" ? "en-US" : "en-US") : "en-US";
但我认为它仅检查节点value.In一些 XML
文件我没有节点名为语言
因此,它给出了一个空引用防爆..
。
如何检查由于节点在 *。xml的存在与否
文件?谢谢你。
But I think its check only for node value.In some xml
file I haven't node called language
So its gives a Null Reference Ex..
.
How to check Given node is exist or not in *.xml
file? Thanks.
推荐答案
东西是空
。你检查空
,所以节点
本身空<选择语言节点/ code>?
Something is null
. You are checking the selected "language" node for null
, so is node
itself null
?
取值$ P $垫code出了更多的线条,嵌套的:
code是不容易跟踪和你不得不重复默认值和函数调用。
Spread the code out over more lines, nested ?:
code is not easy to follow and you have had to repeat default values and function calls.
使用变量,如一个 node.SelectSingleNode(语言)
这样你就不会做两次。这将帮助您找到的bug。
Use variables, such as one for node.SelectSingleNode("language")
so you don't do that twice. And this will help you find the bug.
string language = "en-US"; //default
if(node!=null)
{
var langNode = node.SelectSingleNode("language");
if(langNode!=null)
{
//now look at langNode.Value, and overwrite language variable, maybe you wanted:
if(langNode.Value != "en")
{
language = langNode.Value;
}
}
}
这篇关于检查XML节点的存在与否?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!