SelectSingleNode:跳过意外的xpath

时间:2012-11-16 13:03:26

标签: xml xml-parsing xsd selectsinglenode parsexml

我正在尝试使用xpath从xml读取值。 我已经创建了XmlNamespaceManager并使用我的xml文件添加了所有前缀,uri对。

我有一组xpaths,我需要遍历所有xpath并从xml中搜索相关数据。

我正在使用以下代码

if (myXmlDocument.DocumentElement != null)
{
    var selectSingleNode = myXmlDocument.DocumentElement.SelectSingleNode(xPath, myNamespaceManager);
    if (selectSingleNode != null) 
        value = selectSingleNode.InnerText; 
}

我的问题是 - 当我传递这样的xpath时,其前缀未在xml中包含(因此我的namespaceManager不包含其前缀或命名空间),它将引发异常“未命名名称空间前缀'XXX'。”

我只是想跳过这些意想不到的xpath。

有什么好的解决方案吗?

1 个答案:

答案 0 :(得分:2)

作为一个快速修复,我使用try catch并检查异常是否为XPathException类型,并且消息包含“Namespace prefix *未定义”然后跳过它,但我真的不喜欢这个。