javascript - 如何通过路径检索特定 XML 节点的值?

标签 javascript xml xpath

我正在寻找这个问题的 Javascript 解决方案:

我有一个通过典型的 AJAX 方法加载的 XML 文档:

var xml = http.responseXML;

考虑以下示例 xml 片段:

<main>
    <primary>
         <enabled>true</enabled>
     </primary>
     <secondary>
         <enabled>true</enabled>
     </secondary>
 </main>

我想通过指定路径获取节点的值,如下所示:

var second_enabled = getNodeValueByPath('main/secondary/enabled', xml);

我找不到任何简洁的方法来做这样的事情。在使用 getElementsByTagName 等之后,我似乎被迫遍历节点集合。

我将如何构造 getNodeValueByPath 方法,或者 Javascript 中是否有一些构造允许这样做?

我不太精通 Javascript。

编辑:这是一个示例,展示了我尝试使用 XPath 以及它是如何失败的:

XML:

<?xml version="1.0" ?>
<main xmlns="example.com">
  <primary>
    <enabled>true</enabled>
  </primary>
  <secondary>
    <enabled>false</enabled>
  </secondary>
</main>

JavaScript:(这些只是相关函数)

function useHttpResponse()
{
    if (http.readyState == 4)
    {
        if(http.status == 200)
        {
            var xml = http.responseXML;
            var evalue = getXMLValueByPath('/main/secondary/enabled', xml);
            alert(evalue);
        }
    }
}

function getXMLValueByPath(nodepath, xml)
{
    var result = xml.evaluate(nodepath, xml, null, XPathResult.STRING_TYPE, null).stringValue;
    return result;
}

我使用的是上面的 JavaScript,没有任何额外的库。我正在使用 Mozilla Firefox 3.6.13,它使用 document.evaluate 方法来选择节点(根据 this information from w3schools )。 此应用程序供内部使用,无需在多个浏览器上运行。

给出这些示例,将出现警告对话框,但不包含任何文本。如果我从 XML 文档中删除字符串 xmlns="example.com",则会显示带有所需文本“false”的警告对话框。

使用 Firebug 调试表明只要声明了命名空间,resultNode 就是一个空字符串。

最佳答案

这是常见问题解答:在 XPath 1.0 中,不带前缀的 QName 测试会选择空(或空)命名空间 URI 下的元素。因此,您需要从输入源 (example.com) 向默认命名空间 URI 注册一个前缀。

如何使用 DOM 3 XPath API 做到这一点?

来自 http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathEvaluator-evaluate

evaluate
Evaluates an XPath expression string and returns a result of the specified type if possible.
Parameters
[...]
resolver of type XPathNSResolver
The resolver permits translation of all prefixes, including the xml namespace prefix, within the XPath expression into appropriate namespace URIs. If this is specified as null, any namespace prefix within the expression will result in DOMException being thrown with the code NAMESPACE_ERR.

来自https://developer.mozilla.org/en/DOM/document.evaluate

var xpathResult = document.evaluate(
 xpathExpression, 
 contextNode, 
 namespaceResolver, 
 resultType, 
 result);
  • namespaceResolver is a function that will be passed any namespace prefixes and should return a string representing the namespace URI associated with that prefix. It will be used to resolve prefixes within the XPath itself, so that they can be matched with the document. null is common for HTML documents or when no namespace prefixes are used.

关注此guide , 你可以使用 document.createNSResolverfunction喜欢:

function nsResolver(prefix) {   
  return prefix == 'ex' ? 'example.com' : null;   
}  

function useHttpResponse()
{
  if (http.readyState == 4)
  {
     if (http.status == 200)
     {
        var xml = http.responseXML;
        var evalue = xml.evaluate('string(/ex:main/ex:secondary/ex:enabled)',
                                  xml,
                                  nsResolver,
                                  XPathResult.STRING_TYPE,
                                  null);
        alert(evalue.stringValue);
     }
  }
}     

关于javascript - 如何通过路径检索特定 XML 节点的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4495569/

相关文章:

java - 如何在不验证或检查 DTD 的情况下设置系统和公共(public) ID?

r - 根据特定模式抓取多个段落

javascript - 处理多个复选框的填充状态

java - 使用 Java 在 Windows 中读取 UTF-8 格式的 xml 文件会出现 "IOException: Invalid byte 2 of 2-byte UTF-8 sequence."错误

检查 "undefined"时 JavaScript 变量值被覆盖

xml - 如何在 XQuery 中检查节点 $N 是否存在于节点序列 $S 中?

xpath - 如何向 xpath 添加评论?

xml - 棘手的 xpath 查询

javascript - 如何安全地从任意html中提取文本内容

php - 如何从 PHP 调用 JavaScript 函数?