在JAVA中使用XPath解析具有不同名称空间的xml [英] Parsing xml that has different namespaces using XPath in JAVA

查看:79
本文介绍了在JAVA中使用XPath解析具有不同名称空间的xml的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做这个小项目,我的任务是读取xml文件并进行解析,以便可以将其存储在类中. 这是xml示例.它是用SOAP编写的,我要做的就是获取

I'm doing this small project and my task was to read a xml file and parse it so that it can be stored in a class. Here's the xml example. it's written in SOAP and what I want to do is get

<ns2:getNewTokenResponse xmlns:ns2="http://abc.examples.com/">

这部分经过解析,并得到了子节点,因此我可以创建一个类,该类具有"nodeName"作为属性,其值为"getNewTokenResponse". +会话密钥

this part parsed and the child nodes so that I can create a class that has 'nodeName' as an attribute with a value of 'getNewTokenResponse'. +session key

<env:Envelope xmlns:env='http://schemas.xmlsoap.org/soap/envelope/'>
    <env:Header>
    </env:Header>
    <env:Body>
        <ns2:getNewTokenResponse xmlns:ns2="http://abc.examples.com/">
            <return>
                {{session.key}}
            </return>
        </ns2:getNewTokenResponse>
    </env:Body>
</env:Envelope>

但是我真正的问题是,我发现了很多很好的示例代码,名称空间没有前缀,并且xml文件的结构可能有所不同.因此,在这里我很困惑地无法完成任务.我将不胜感激任何建议.干杯:D

But my real problem is, I found many good example codes, namespaces are not prefixed and structure of xml file can vary. So here I am being confused to achieve the task. I'll appreciate any advice. Cheers:D

推荐答案

要使用Java中的命名空间进行XPath查询,我相信您需要执行以下操作:

To do an XPath query with namespaces in Java, I believe you need to do something like this:

XPath xpath = XPathFactory.newInstance().newXPath();
xpath.setNamespaceContext(new NamespaceContext() {
    @Override
    public String getNamespaceURI(String prefix) {
        switch (prefix) {
            case "env":
                return "http://schemas.xmlsoap.org/soap/envelope/";
            case "ns2":
                return "http://abc.examples.com/";
        }

        return XMLConstants.NULL_NS_URI;
    }

    @Override
    public String getPrefix(String namespaceURI) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public Iterator getPrefixes(String namespaceURI) {
        throw new UnsupportedOperationException("Not supported yet.");
    }
});

Node getNewTokenResp = 
     (Node) xpath.evaluate("/env:Envelope/env:Body/ns2:getNewTokenResponse", 
     document, XPathConstants.NODE);

在创建DocumentBuilder来解析文档之前,还需要在DocumentBuilderFactory上调用.setNamespaceAware(true);.

You also need to call .setNamespaceAware(true); on your DocumentBuilderFactory before you create the DocumentBuilder to parse your document.

这篇关于在JAVA中使用XPath解析具有不同名称空间的xml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆