使用xpaths从xml标记中获取相同名称的值

时间:2017-04-25 15:09:42

标签: java xpath xml-parsing

我在服务器上发布了一些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 标记的值。

我需要从“ TransportationEvent ”标记中选择数据,其中“ creationDateTime ”等于今天的日期。

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

我希望获得 ctx 的值,其中包含最新 TransportationEvent 标记的上下文。

我知道我错过了什么。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

使用谓词中的import boto3 pipeline = boto3.client('codepipeline') def lambda_handler(event, context): # stuff response = pipeline.put_job_success_result( jobId=event['CodePipeline.job']['id'] ) return response 函数仅选择最后一个last()

TransportationEvent
相关问题