如果处理节点 X 是可选的,那么您的代码应类似于:
if(node X exists in file)
{
do work with X
}
并不是:
try
{
do work with X
}
catch{}
现在,如果除了尝试使用节点 X 之外无法确定节点 X 是否存在,或者如果在检查节点 X 是否存在后可以将其删除,那么您将被迫使用 try/catch模型。这不是这里的情况。(与说,在读取文件之前检查文件是否存在相反;有人可以在您检查文件是否存在后将其删除。)
-------------------------------------------------- ----------
编辑:
由于您的问题似乎是在以下 XML 中单独访问节点“孙子”,其中“父”可能不存在。(请原谅我在 SO 中呈现此 XML 的能力很差;知识渊博的读者可以随意以适当的格式进行编辑。)
<root>
<Parent>
<Child>
<GrandChild>
The data I really want.
</GrandChild>
</Child>
</Parent>
</root>
为此,我会做这样的事情:
public static class XMLHelpers
{
public static Node GetChild(this Node parent, string tagName)
{
if(parent == null) return null;
return parent.GetNodeByTagName(tagName);
}
}
然后你可以这样做:
var grandbaby = rootNode.GetChild("Parent").GetChild("Child").GetChild("GrandChild");
if(grandbaby != null)
{
//use grandbaby
}