【问题标题】:Get value from xml tags which are of same name using xpaths使用 xpaths 从同名的 xml 标签中获取值
【发布时间】:2017-04-25 15:09:42
【问题描述】:

我在服务器上发布了一些 csv 输入文件,它给了我一个如下所示的 xml 文件:

<ns0:TransportationEvent xmlns:ns0="http://www.server.com/schemas/TransportationEvent.xsd">
<ns0:creationDateTime>2017-04-06</ns0:creationDateTime>
.....
.....
</ns0:TransportationEvent>

<ns0:TransportationEvent xmlns:ns0="http://www.fedex.com/schemas/TransportationEvent.xsd">
<ns0:creationDateTime>2017-04-25</ns0:creationDateTime>
.....
.....
</ns0:TransportationEvent>

TransportationEvent 标记将一次又一次地添加,其中包含更新日期。

我正在使用 XpathFactory 类和 NamespaceContext 类从这个 xml 中检索数据,如下所示:

NamespaceContext ctx = new NamespaceContext() { 
        public String getNamespaceURI(String prefix) { 
            String uri; 
            if (prefix.equals("ns0")) 
                uri = "http://www.server.com/schemas/TransportationEvent.xsd"; 
            else 
                uri = null; 
            return uri; 
        } 
        public Iterator getPrefixes(String val) { 
            return null; 
        } 
        // Dummy implementation - not used! 
        public String getPrefix(String uri) { 
            return null; 
        } 
    };

XPathFactory xpathFact = XPathFactory.newInstance();
XPath xpath = xpathFact.newXPath();
xpath.setNamespaceContext(ctx);

String strXpath = "//ns0:TransportationEvent/ns0:creationDateTime/text()";       
String creationDateTime = xpath.evaluate(strXpath, doc);

以上代码将 creationDateTime 的值设为 2017-04-06。基本上它总是从第一个 TransportationEvent 标签中获取值。

我需要从“creationDateTime”等于今天的日期的“TransportationEvent”标签中挑选数据。

我可以通过使用 NodeList 类来执行此操作,并且可以遍历所有“TransportationEvent”标签,但是我将无法使用 Xpath 或 NamespaceContext 实现。我发现 NodeList 类和 NamespaceContext 类或 Xpath 类之间没有任何联系。

我想获取 ctx 的值,它具有最新的 TransportationEvent 标签的上下文。

我知道我错过了一些东西。有人可以帮忙吗?

【问题讨论】:

    标签: java xpath xml-parsing


    【解决方案1】:

    在谓词中使用last() 函数仅选择最后一个TransportationEvent

    String strXpath = "//ns0:TransportationEvent[last()]/ns0:creationDateTime/text()";     
    

    【讨论】:

    • 这就像我想要的那样工作。谢谢。这是使用 Namespacecontext 和 xpathFactory 类解析 xml 的好方法吗?我有其中包含大量内容的 xml 文件。使用 nodeList 和节点会使代码难以管理。我在吗?
    • 你是正确的。使用节点方法在 DOM 中导航完全不可读,而 XPath 非常简短。
    猜你喜欢
    • 1970-01-01
    • 2012-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-27
    • 1970-01-01
    • 2018-06-09
    • 1970-01-01
    相关资源
    最近更新 更多