草庐IT

java - 为什么只有某些 XPath 表达式在 xml 具有 namespace 前缀时找到节点

coder 2024-03-13 原文

在下面的示例代码中,当源 xml 具有命名空间前缀时,形式为 '//elementName' 的任何 XPath 都返回 null(请参阅 testWithNS()底部的代码)。

当源 xml 没有命名空间前缀时,所有列出的 XPath 表达式都返回一个节点(参见 testNoNS())。

我知道我可以通过设置 NamespaceContext(如 testWithNSContext())、将 xml 解析为命名空间感知文档并在 XPath 中使用命名空间前缀来解决此问题。但是我不想这样做,因为我的实际代码需要处理带有和不带有命名空间前缀的 xml。

我的问题是为什么只有:

  • //测试
  • // child 1
  • //孙子1
  • // child 2

返回 null,而 testWithNS() 中的所有其他示例都返回节点?

输出

testNoNS()
test = found
/test = found
//test = found
//test/* = found
//test/child1 = found
//test/child1/grandchild1 = found
//test/child2 = found
//child1 = found
//grandchild1 = found
//child1/grandchild1 = found
//child2 = found

testWithNS()
test = found
/test = found
//test = *** NOT FOUND ***
//test/* = found
//test/child1 = found
//test/child1/grandchild1 = found
//test/child2 = found
//child1 = *** NOT FOUND ***
//grandchild1 = *** NOT FOUND ***
//child1/grandchild1 = found
//child2 = *** NOT FOUND ***

testWithNSContext()
ns1:test = found
/ns1:test = found
//ns1:test = found
//ns1:test/* = found
//ns1:test/ns1:child1 = found
//ns1:test/ns1:child1/ns1:grandchild1 = found
//ns1:test/ns1:child2 = found
//ns1:child1 = found
//ns1:grandchild1 = found
//ns1:child1/ns1:grandchild1 = found
//ns1:child2 = found

代码

import java.io.StringReader;
import java.util.Iterator;

import javax.xml.XMLConstants;
import javax.xml.namespace.NamespaceContext;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.junit.Test;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;

public class XPathBugTest {

    private String xmlDec = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>";
    private String xml = xmlDec + 
        "<test>" +
        "  <child1>" +
        "    <grandchild1/>" +
        "  </child1>" +
        "  <child2/>" +
        "</test>";
    private String xmlNs = xmlDec + 
        "<ns1:test xmlns:ns1=\"http://www.wfmc.org/2002/XPDL1.0\">" +
        "  <ns1:child1>" +
        "    <ns1:grandchild1/>" +
        "  </ns1:child1>" +
        "  <ns1:child2/>" +
        "</ns1:test>";

    final XPathFactory xpathFactory = XPathFactory.newInstance();
    final XPath xpath = xpathFactory.newXPath();

    @Test
    public void testNoNS() throws Exception {
        System.out.println("\ntestNoNS()");
        final Document doc = getDocument(xml);

        isFound("test", xpath.evaluate("test", doc, XPathConstants.NODE));
        isFound("/test", xpath.evaluate("/test", doc, XPathConstants.NODE));
        isFound("//test", xpath.evaluate("//test", doc, XPathConstants.NODE));
        isFound("//test/*", xpath.evaluate("//test/*", doc, XPathConstants.NODE));
        isFound("//test/child1", xpath.evaluate("//test/child1", doc, XPathConstants.NODE));
        isFound("//test/child1/grandchild1", xpath.evaluate("//test/child1/grandchild1", doc, XPathConstants.NODE));
        isFound("//test/child2", xpath.evaluate("//test/child2", doc, XPathConstants.NODE));
        isFound("//child1", xpath.evaluate("//child1", doc, XPathConstants.NODE));
        isFound("//grandchild1", xpath.evaluate("//grandchild1", doc, XPathConstants.NODE));
        isFound("//child1/grandchild1", xpath.evaluate("//child1/grandchild1", doc, XPathConstants.NODE));
        isFound("//child2", xpath.evaluate("//child2", doc, XPathConstants.NODE));
    }

    @Test
    public void testWithNS() throws Exception {
        System.out.println("\ntestWithNS()");
        final Document doc = getDocument(xmlNs);

        isFound("test", xpath.evaluate("test", doc, XPathConstants.NODE));
        isFound("/test", xpath.evaluate("/test", doc, XPathConstants.NODE));
        isFound("//test", xpath.evaluate("//test", doc, XPathConstants.NODE));
        isFound("//test/*", xpath.evaluate("//test/*", doc, XPathConstants.NODE));
        isFound("//test/child1", xpath.evaluate("//test/child1", doc, XPathConstants.NODE));
        isFound("//test/child1/grandchild1", xpath.evaluate("//test/child1/grandchild1", doc, XPathConstants.NODE));
        isFound("//test/child2", xpath.evaluate("//test/child2", doc, XPathConstants.NODE));
        isFound("//child1", xpath.evaluate("//child1", doc, XPathConstants.NODE));
        isFound("//grandchild1", xpath.evaluate("//grandchild1", doc, XPathConstants.NODE));
        isFound("//child1/grandchild1", xpath.evaluate("//child1/grandchild1", doc, XPathConstants.NODE));
        isFound("//child2", xpath.evaluate("//child2", doc, XPathConstants.NODE));
    }

    @Test
    public void testWithNSContext() throws Exception {
        System.out.println("\ntestWithNSContext()");
        final Document doc = getDocumentNS(xmlNs);

        xpath.setNamespaceContext(new MyNamespaceContext());

        isFound("ns1:test", xpath.evaluate("ns1:test", doc, XPathConstants.NODE));
        isFound("/ns1:test", xpath.evaluate("/ns1:test", doc, XPathConstants.NODE));
        isFound("//ns1:test", xpath.evaluate("//ns1:test", doc, XPathConstants.NODE));
        isFound("//ns1:test/*", xpath.evaluate("//ns1:test/*", doc, XPathConstants.NODE));
        isFound("//ns1:test/ns1:child1", xpath.evaluate("//ns1:test/ns1:child1", doc, XPathConstants.NODE));
        isFound("//ns1:test/ns1:child1/ns1:grandchild1", xpath.evaluate("//ns1:test/ns1:child1/ns1:grandchild1", doc, XPathConstants.NODE));
        isFound("//ns1:test/ns1:child2", xpath.evaluate("//ns1:test/ns1:child2", doc, XPathConstants.NODE));
        isFound("//ns1:child1", xpath.evaluate("//ns1:child1", doc, XPathConstants.NODE));
        isFound("//ns1:grandchild1", xpath.evaluate("//ns1:grandchild1", doc, XPathConstants.NODE));
        isFound("//ns1:child1/ns1:grandchild1", xpath.evaluate("//ns1:child1/ns1:grandchild1", doc, XPathConstants.NODE));
        isFound("//ns1:child2", xpath.evaluate("//ns1:child2", doc, XPathConstants.NODE));
    }

    private void isFound(String xpath, Object object) {
        System.out.println(xpath + " = " + (object == null ? "*** NOT FOUND ***" : "found"));
    }

    private Document getDocument(final String xml) throws Exception {
        final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        return factory.newDocumentBuilder().parse(new InputSource(new StringReader(xml)));        
    }

    private Document getDocumentNS(final String xml) throws Exception {
        final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        return factory.newDocumentBuilder().parse(new InputSource(new StringReader(xml)));
    }

    public class MyNamespaceContext implements NamespaceContext {
        @Override
        public String getNamespaceURI(String prefix) {
            if ("ns1".equals(prefix)) {
                return "http://www.wfmc.org/2002/XPDL1.0";
            }
            return XMLConstants.NULL_NS_URI;
        }
        @Override
        public String getPrefix(String uri) {
            throw new UnsupportedOperationException();
        }
        @Override
        public Iterator getPrefixes(String uri) {
            throw new UnsupportedOperationException();
        }
    }
}

在 Saxon 测试之后更新

我现在已经使用 Saxon 将 XPahtFactory 行更改为此来测试相同的代码

final XPathFactory xpathFactory = new net.sf.saxon.xpath.XPathFactoryImpl();

testWithNS() 中使用 Saxon 所有行返回 *** NOT FOUND *** 而不仅仅是像 '//elementName' 与默认的 Xalan 实现一样。

鉴于我正在使用非命名空间感知文档生成器工厂来解析 xml,为什么这些 xpath 都不起作用,而只有一些与 Xalan 一起工作?

最佳答案

如果要忽略命名空间,可以使用local-name XPath 函数:

//*[local-name()='grandchild1']

关于java - 为什么只有某些 XPath 表达式在 xml 具有 namespace 前缀时找到节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17835232/

有关java - 为什么只有某些 XPath 表达式在 xml 具有 namespace 前缀时找到节点的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  3. ruby-on-rails - Rails - 子类化模型的设计模式是什么? - 2

    我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co

  4. ruby - 具有身份验证的私有(private) Ruby Gem 服务器 - 2

    我想安装一个带有一些身份验证的私有(private)Rubygem服务器。我希望能够使用公共(public)Ubuntu服务器托管内部gem。我读到了http://docs.rubygems.org/read/chapter/18.但是那个没有身份验证-如我所见。然后我读到了https://github.com/cwninja/geminabox.但是当我使用基本身份验证(他们在他们的Wiki中有)时,它会提示从我的服务器获取源。所以。如何制作带有身份验证的私有(private)Rubygem服务器?这是不可能的吗?谢谢。编辑:Geminabox问题。我尝试“捆绑”以安装新的gem..

  5. ruby - 什么是填充的 Base64 编码字符串以及如何在 ruby​​ 中生成它们? - 2

    我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%

  6. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  7. ruby - 为什么 4.1%2 使用 Ruby 返回 0.0999999999999996?但是 4.2%2==0.2 - 2

    为什么4.1%2返回0.0999999999999996?但是4.2%2==0.2。 最佳答案 参见此处:WhatEveryProgrammerShouldKnowAboutFloating-PointArithmetic实数是无限的。计算机使用的位数有限(今天是32位、64位)。因此计算机进行的浮点运算不能代表所有的实数。0.1是这些数字之一。请注意,这不是与Ruby相关的问题,而是与所有编程语言相关的问题,因为它来自计算机表示实数的方式。 关于ruby-为什么4.1%2使用Ruby返

  8. ruby-on-rails - 如何从 format.xml 中删除 <hash></hash> - 2

    我有一个对象has_many应呈现为xml的子对象。这不是问题。我的问题是我创建了一个Hash包含此数据,就像解析器需要它一样。但是rails自动将整个文件包含在.........我需要摆脱type="array"和我该如何处理?我没有在文档中找到任何内容。 最佳答案 我遇到了同样的问题;这是我的XML:我在用这个:entries.to_xml将散列数据转换为XML,但这会将条目的数据包装到中所以我修改了:entries.to_xml(root:"Contacts")但这仍然将转换后的XML包装在“联系人”中,将我的XML代码修改为

  9. ruby - ruby 中的 TOPLEVEL_BINDING 是什么? - 2

    它不等于主线程的binding,这个toplevel作用域是什么?此作用域与主线程中的binding有何不同?>ruby-e'putsTOPLEVEL_BINDING===binding'false 最佳答案 事实是,TOPLEVEL_BINDING始终引用Binding的预定义全局实例,而Kernel#binding创建的新实例>Binding每次封装当前执行上下文。在顶层,它们都包含相同的绑定(bind),但它们不是同一个对象,您无法使用==或===测试它们的绑定(bind)相等性。putsTOPLEVEL_BINDINGput

  10. ruby - Infinity 和 NaN 的类型是什么? - 2

    我可以得到Infinity和NaNn=9.0/0#=>Infinityn.class#=>Floatm=0/0.0#=>NaNm.class#=>Float但是当我想直接访问Infinity或NaN时:Infinity#=>uninitializedconstantInfinity(NameError)NaN#=>uninitializedconstantNaN(NameError)什么是Infinity和NaN?它们是对象、关键字还是其他东西? 最佳答案 您看到打印为Infinity和NaN的只是Float类的两个特殊实例的字符串

随机推荐