【问题标题】:XPath issue using JDOM / Jaxen使用 JDOM / Jaxen 的 XPath 问题
【发布时间】:2012-01-19 09:06:25
【问题描述】:

在我的程序中,我正在下载一个 xml 文件,如下所示。

提取所有属性的任务应该很简单 货币和汇率。

我正在使用JDOM,并开始如下:

try {
    // TODO code application logic here
    SAXBuilder builder = new SAXBuilder();
    org.jdom.Document doc = builder.build("test.xml");
    List<?> all = XPath.selectNodes(doc, "/Envelope/Cube/Cube/@currency");
    for(Object o : all) {
        Attribute att = (Attribute) o;
        System.out.println("ausgbabe: " + att);
    }
}

已经测试了几种获取条目的路径,但都不起作用。

<?xml version="1.0" encoding="UTF-8"?> 
<gesmes:Envelope xmlns:gesmes="http://www.gesmes.org/xml/2002-08-01" xmlns="http://www.ecb.int/vocabulary/2002-08-01/eurofxref"> 
    <gesmes:subject>Reference rates</gesmes:subject> 
    <gesmes:Sender> 
        <gesmes:name>European Central Bank</gesmes:name> 
    </gesmes:Sender> 
    <Cube> 
        <Cube time='2012-01-17'> 
            <Cube currency='USD' rate='1.2790'/> 
            <Cube currency='JPY' rate='98.20'/> 
            <Cube currency='BGN' rate='1.9558'/> 
            <Cube currency='CZK' rate='25.650'/> 
            <Cube currency='DKK' rate='7.4353'/> 
            <Cube currency='GBP' rate='0.83045'/> 
        </Cube> 
    </Cube> 
</gesmes:Envelope>

【问题讨论】:

    标签: java xml xpath


    【解决方案1】:

    您需要将命名空间绑定到您的 xpath 对象。您应该像这样创建 xpath 对象(我必须向您的 xpath 添加一个新的 Cube 条目):

    XPath xpath = XPath.newInstance("/gesmes:Envelope/root:Cube/root:Cube/root:Cube/@currency");
    

    然后添加你的命名空间声明:

    xpath.addNamespace("gesmes", "http://www.gesmes.org/xml/2002-08-01");
    xpath.addNamespace("root", "http://www.ecb.int/vocabulary/2002-08-01/eurofxref");
    

    实际上,Envelope 元素具有“http://www.gesmes.org/xml/2002-08-01”命名空间 uri,而所有 Cube 元素都有“http://www.ecb.int” /vocabulary/2002-08-01/eurofxref" 命名空间 uri,声明为默认命名空间。您可以在 xpath 中使用所需的命名空间前缀,但 uri 必须匹配。
    然后使用您创建的 xpath 像这样搜索文档:

    List<?> all = xpath.selectNodes(doc);
    

    我用你的 xml 测试了这段代码,它产生了以下输出:

    ausgbabe: [Attribute: currency="USD"]
    ausgbabe: [Attribute: currency="JPY"]
    ausgbabe: [Attribute: currency="BGN"]
    ausgbabe: [Attribute: currency="CZK"]
    ausgbabe: [Attribute: currency="DKK"]
    ausgbabe: [Attribute: currency="GBP"]
    

    【讨论】:

    • 实际上,按照你的方式改代码后就不行了。
    • 好吧,我用你的 xml 尝试了这段代码,它可以工作。我将输出添加到我的答案中。您能否检查一下您是否在代码中复制了所有三个片段?
    • 是的,它有效。问题是由默认命名空间引起的。 @javanna
    • 是的,默认命名空间很棘手。我对我的回答加了一点解释。那么,你解决了吗?
    • 感谢您的回答,但问题不是我提出的。 @javanna
    【解决方案2】:

    您的 xml 中有名称空间,您没有告诉 XPath 引擎。您需要使用javax.xml.namespace.NamespaceContext。请参阅 this article 以获得完整的解释和指导以使其正常工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-26
      • 2012-08-10
      • 2013-04-25
      • 1970-01-01
      • 1970-01-01
      • 2022-11-18
      • 1970-01-01
      • 2012-04-02
      相关资源
      最近更新 更多