使用 xpath 在 Java 中使用名称空间解析 XML

Posted

技术标签:

【中文标题】使用 xpath 在 Java 中使用名称空间解析 XML【英文标题】:Parse XML with namespaces in Java using xpath 【发布时间】:2012-07-23 14:31:17 【问题描述】:

我正在尝试在 java 中解析 SOAP 请求,但代码没有返回任何节点 这是任何人都可以找到错误的代码

        String xml="<soapenv:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ser=\"http://services.web.post.list.com\"><soapenv:Header><authInfo xsi:type=\"soap:authentication\" xmlns:soap=\"http://list.com/services/SoapRequestProcessor\"><!--You may enter the following 2 items in any order--><username xsi:type=\"xsd:string\">dfasf@google.com</username><password xsi:type=\"xsd:string\">PfasdfRem91</password></authInfo></soapenv:Header></soapenv:Envelope>"; 
    System.out.println(xml);
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true);
    DocumentBuilder builder = domFactory.newDocumentBuilder();
    Document doc = builder.parse(new InputSource(new StringReader(xml)));
    XPath xpath = XPathFactory.newInstance().newXPath();
    // XPath Query for showing all nodes value

    try
    
    XPathExpression expr = xpath.compile("/soapenv:Envelope/soapenv:Header/authInfo/password");
    Object result = expr.evaluate(doc, XPathConstants.NODESET);
    NodeList nodes = (NodeList) result;
    System.out.println("Got " + nodes.getLength() + " nodes");
//    System.out.println(nodes.item(0).getNodeValue());
    
    catch(Exception E)
    
        System.out.println(E);
    

【问题讨论】:

试试这些:***.com/questions/5673708/…***.com/questions/5519766/… 【参考方案1】:

你需要在XPath上设置一个NamespaceContext

演示

package forum11644994;

import java.io.StringReader;
import java.util.Iterator;

import javax.xml.namespace.NamespaceContext;
import javax.xml.parsers.*;
import javax.xml.xpath.*;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class Demo 

    public static void main(String[] args) throws Exception 
        String xml = "<soapenv:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ser=\"http://services.web.post.list.com\"><soapenv:Header><authInfo xsi:type=\"soap:authentication\" xmlns:soap=\"http://list.com/services/SoapRequestProcessor\"><!--You may enter the following 2 items in any order--><username xsi:type=\"xsd:string\">dfasf@google.com</username><password xsi:type=\"xsd:string\">PfasdfRem91</password></authInfo></soapenv:Header></soapenv:Envelope>";
        System.out.println(xml);
        DocumentBuilderFactory domFactory = DocumentBuilderFactory
                .newInstance();
        domFactory.setNamespaceAware(true);
        DocumentBuilder builder = domFactory.newDocumentBuilder();
        Document doc = builder.parse(new InputSource(new StringReader(xml)));
        XPath xpath = XPathFactory.newInstance().newXPath();
        xpath.setNamespaceContext(new NamespaceContext() 

            @Override
            public Iterator getPrefixes(String arg0) 
                return null;
            

            @Override
            public String getPrefix(String arg0) 
                return null;
            

            @Override
            public String getNamespaceURI(String arg0) 
                if("soapenv".equals(arg0)) 
                    return "http://schemas.xmlsoap.org/soap/envelope/";
                
                return null;
            
        );
        // XPath Query for showing all nodes value

        try 
            XPathExpression expr = xpath
                    .compile("/soapenv:Envelope/soapenv:Header/authInfo/password");
            Object result = expr.evaluate(doc, XPathConstants.NODESET);
            NodeList nodes = (NodeList) result;
            System.out.println("Got " + nodes.getLength() + " nodes");
            // System.out.println(nodes.item(0).getNodeValue());
         catch (Exception E) 
            System.out.println(E);
        

    

输出

<soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://services.web.post.list.com"><soapenv:Header><authInfo xsi:type="soap:authentication" xmlns:soap="http://list.com/services/SoapRequestProcessor"><!--You may enter the following 2 items in any order--><username xsi:type="xsd:string">dfasf@google.com</username><password xsi:type="xsd:string">PfasdfRem91</password></authInfo></soapenv:Header></soapenv:Envelope>
Got 1 nodes

【讨论】:

【参考方案2】:

在最新回复中添加更多内容.. 要获得特定的节点值,您可以使用以下 - [System.out.println(nodes.item(0).getTextContent());]

【讨论】:

以上是关于使用 xpath 在 Java 中使用名称空间解析 XML的主要内容,如果未能解决你的问题,请参考以下文章

java中使用xpath读取xml指定节点的属性的名称列表

XPATHS和默认命名空间

如何使用 xpath 选择名称空间定义标记

如何使用 XPath 忽略命名空间

为啥命名空间限定节点没有 XPath 语法?

在 Java 中使用 XPath 解析 XML [重复]