【问题标题】:Multiple NameSpace in Xml Xpath valueXml Xpath 值中的多个命名空间
【发布时间】:2012-12-06 04:21:04
【问题描述】:

在 Java 中为 Xmls 使用 Xpath 解析是个新手。但是我学会了它并且它工作得很好,直到下面的这个问题不确定如何遍历到这个 .请找到下面的代码,让我知道需要更正的地方。

package test;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.TransformerException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

public class CallTestcall {
    public static void main(String[] args) throws Exception {

        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setNamespaceAware(true);
        DocumentBuilder builder = domFactory.newDocumentBuilder();

        String responsePath1 = "C:/Verizon/webserviceTestTool/generatedResponse/example.xml";
        Document doc1 = builder.parse(responsePath1);

        String responsePath0 = "C:/Verizon/webserviceTestTool/generatedResponse/response.xml";
        Document doc0 = builder.parse(responsePath0);

        example0(doc0);
        example1(doc1);
    }

    private static void example0(Document example)
            throws XPathExpressionException, TransformerException {
        System.out.println("\n*** First example - namespacelookup hardcoded ***");

        XPath xPath = XPathFactory.newInstance().newXPath();
        xPath.setNamespaceContext(new HardcodedNamespaceResolver());


        String result = xPath.evaluate("s:Envelope/s:Body/ns1:UpdateSessionResponse",
                example);

        // I tried all the Values to traverse further to UpdateSessionResult but am not able to I used the following xpath expressions

        result = xPath.evaluate("s:Envelope/s:Body/ns1:UpdateSessionResponse/a:UpdateSessionResult",
                example);

        result = xPath.evaluate("s:Envelope/s:Body/ns1:UpdateSessionResponse/i:UpdateSessionResult",
                example);

        System.out.println("example0 : "+result);
    }

    private static void example1(Document example)
            throws XPathExpressionException, TransformerException {
        System.out.println("\n*** First example - namespacelookup hardcoded ***");

        XPath xPath = XPathFactory.newInstance().newXPath();
        xPath.setNamespaceContext(new HardcodedNamespaceResolver());

        String result = xPath.evaluate("books:booklist/technical:book/:author",
                example);
        System.out.println("example1 : "+result);
    }

}

请在我添加了前缀的地方找到实现 nameSpaceContext 的类

package test;

import java.util.Iterator;
import javax.xml.XMLConstants;
import javax.xml.namespace.NamespaceContext;

public class HardcodedNamespaceResolver implements NamespaceContext {



/**
     * This method returns the uri for all prefixes needed. Wherever possible it
     * uses XMLConstants.
     * 
     * @param prefix
     * @return uri
     */
    public String getNamespaceURI(String prefix) {
        if (prefix == null) {
            throw new IllegalArgumentException("No prefix provided!");
        } else if (prefix.equals(XMLConstants.DEFAULT_NS_PREFIX)) {
            return "http://univNaSpResolver/book";
        } else if (prefix.equals("books")) {
            return "http://univNaSpResolver/booklist";
        } else if (prefix.equals("fiction")) {
            return "http://univNaSpResolver/fictionbook";
        } else if (prefix.equals("technical")) {
            return "http://univNaSpResolver/sciencebook";
        } else if (prefix.equals("s")) {
            return "http://schemas.xmlsoap.org/soap/envelope/";
        } else if (prefix.equals("a")) {
            return "http://channelsales.corp.cox.com/vzw/v1/data/";
        } else if (prefix.equals("i")) {
            return "http://www.w3.org/2001/XMLSchema-instance";
        } else if (prefix.equals("ns1")) {
            return "http://channelsales.corp.cox.com/vzw/v1/";
        } 


        else {
            return XMLConstants.NULL_NS_URI;
        }
    }

    public String getPrefix(String namespaceURI) {
        // Not needed in this context.
        return null;
    }

    public Iterator getPrefixes(String namespaceURI) {
        // Not needed in this context.
        return null;
    }

}

请找到我的 Xml ::::

String XmlString  = "<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"><s:Body><UpdateSessionResponse xmlns="http://channelsales.corp.cox.com/vzw/v1/"><UpdateSessionResult xmlns:a="http://channelsales.corp.cox.com/vzw/v1/data/" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<a:ResponseHeader>
<a:SuccessFlag>true</a:SuccessFlag>
<a:ErrorCode i:nil="true"/>
<a:ErrorMessage i:nil="true"/>
<a:Timestamp>2012-12-05T15:28:35.5363903-05:00</a:Timestamp>
</a:ResponseHeader>
<a:SessionId>cd3ce09e-eb33-48e8-b628-ecd406698aee</a:SessionId>
<a:CacheKey i:nil="true"/>

【问题讨论】:

    标签: java xml xpath xml-parsing


    【解决方案1】:

    试试下面的。它对我有用。

      result = xPath.evaluate("/s:Envelope/s:Body/ns1:UpdateSessionResponse/ns1:UpdateSessionResult",
                      example);
    

    因为您是从文档的根目录开始搜索,所以在 xpath 表达式之前加上一个正斜杠 (/)

    此外,在下面的 XML 片段中,字符串 xmlns="http... 表示您将其设置为默认命名空间。在您的名称空间解析器中,您为此提供了前缀 ns1。所以即使UpdateSessionResult 定义了两个命名空间前缀ai,它本身并不使用这些前缀(例如&lt;a:UpdateSessionResult...),因此它属于默认命名空间(命名为'ns1')

    <UpdateSessionResponse xmlns="http://channelsales.corp.cox.com/vzw/v1/">
    <UpdateSessionResult xmlns:a="http://channelsales.corp.cox.com/vzw/v1/data/"  xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
    

    这就是为什么您需要使用ns1:UpdateSessionResult 而不是a:UpdateSessionResulti:UpdateSessionResult

    【讨论】:

    • 非常感谢你让我开心。我昨天尝试了很多来解决,但实际上我可以继续进行,尽管 updateSessionResult 有两个命名空间,但它本身不使用这些前缀,所以它采用默认的一个。我是多么愚蠢:(..无论如何非常感谢:):)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-07
    • 1970-01-01
    • 1970-01-01
    • 2011-07-24
    • 2014-04-19
    • 1970-01-01
    • 2011-01-05
    相关资源
    最近更新 更多