【问题标题】:SelectSingleNode : skip unexpected xpathSelectSingleNode : 跳过意外的 xpath
【发布时间】:2012-11-16 13:03:26
【问题描述】:

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

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

我正在使用下面的代码

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

我的问题是——当我传递这样的 xpath,其前缀没有包含在 xml 中(所以我的 namespaceManager 不包含它的前缀或命名空间),它会抛出一个异常“命名空间前缀 'XXX' 没有定义。”

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

有什么好的解决办法吗?

【问题讨论】:

    标签: xml xml-parsing xsd selectsinglenode parsexml


    【解决方案1】:

    作为一个快速修复,我正在使用 try catch 并检查异常是否属于 XPathException 类型并且消息是否包含“未定义命名空间前缀 *”然后跳过它,但我真的不喜欢这样。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-05
      相关资源
      最近更新 更多