簡體   English   中英

如何在Java中使用xPath從包含名稱空間的xml中提取元素值?

[英]How to extract element value from an xml containing namespaces with xPath in Java?

環境: Windows 10,Eclipse,Java 1.5

目標:我正在嘗試使用xPath獲取xml的元素文本值。 xml包含各種名稱空間。

問題:我總是得到一個空值。

我在SO上檢查了一些線程,但是沒有任何效果。 xml絕對路徑在瀏覽器上可以正常打開。

這就是我所擁有的:

//Initialize objects
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
builderFactory.setNamespaceAware(true);
builder = builderFactory.newDocumentBuilder();
Document xmlDocument = builder.parse(xmlFINAL);//File with absolute path
XPath xPath = (XPath) XPathFactory.newInstance().newXPath();  

//NamespaceContext used for xPath
NamespaceContext nsContext = new NamespaceContext (){
public String getNamespaceURI(String prefix) {
                 if (prefix == null) {            
                        throw new NullPointerException("Null prefix");
                  } else if ("ns2".equals(prefix)) {            
                        return "http://ns2";
                  }else{
                      return "http://ns1";
                  }

            }

            public String getPrefix(String namespaceURI) {
                return null;
            }

            public Iterator getPrefixes(String namespaceURI) {
                return null;
            }

        };
xPath.setNamespaceContext(nsContext);

這是文檔內容的一部分

測試xml(我的太大):

<root_element xmlns="http://ns1" xmlns:ns2="http://ns2">
    <element1>
    ...
        <ns2:element2>
            <ns2:element3>I want this text</element3>
        </element2>
    ...
    </element1>
</root_element >

獲取元素值(始終返回"" ):

String expression = "/root_element/element1/ns2:element2/ns2:element3/text()";
String valor = (String) xPath.compile(expression).evaluate(xmlDocument,XPathConstants.STRING);
//or
String valor = xPath.evaluate(expression, xmlDocument);

這樣工作正常:

public static void main(String[] args) throws Exception {
        XPathFactory xpf = XPathFactory.newInstance();
        XPath path = xpf.newXPath();
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        DocumentBuilder builder = factory.newDocumentBuilder();

        File fileXML = new File("test.xml");
        Document xml = builder.parse(fileXML);
        Element dataset = xml.getDocumentElement();

        NamespaceContext ns = new NamespaceContext() {
            @Override
            public Iterator getPrefixes(String namespaceURI) {
                return null;
            }

            @Override
            public String getPrefix(String namespaceURI) {
                return namespaceURI.equalsIgnoreCase("http://ns1") ? "ns1" : namespaceURI.equalsIgnoreCase("http://ns2") ? "ns2" : "";
            }

            @Override
            public String getNamespaceURI(String prefix) {
                return prefix.equalsIgnoreCase("ns1") ? "http://ns1" : prefix.equalsIgnoreCase("ns2") ? "http://ns2" : "";
            }
        };

        path.setNamespaceContext(ns);

        String exp1 = "/root_element";
        Node root = (Node) path.evaluate(exp1, dataset, XPathConstants.NODE);
        System.out.println(root.getNodeName() + " has " + root.getChildNodes().getLength() + " childrens (text included).");

        exp1 = "/root_element/element1";
        root = (Node) path.evaluate(exp1, dataset, XPathConstants.NODE);
        System.out.println(root.getNodeName() + " has " + root.getChildNodes().getLength() + " childrens (text included).");

        exp1 = "/root_element/element1/ns2:element2";
        root = (Node) path.evaluate(exp1, dataset, XPathConstants.NODE);
        System.out.println(root.getNodeName() + " has " + root.getChildNodes().getLength() + " childrens (text included).");

        exp1 = "/root_element//ns2:element3";
        root = (Node) path.evaluate(exp1, dataset, XPathConstants.NODE);
        System.out.println(root.getNodeName() + " has " + root.getChildNodes().getLength() + " childrens (text included).");

        exp1 = "/root_element//ns2:element3/text()";
        String text = (String) path.evaluate(exp1, dataset, XPathConstants.STRING);
        System.out.println("Text = " + text);
    }

我使用的XML:

<root_element xmlns="" xmlns:ns1="http://ns1" xmlns:ns2="http://ns2">
    <element1>
        <ns2:element2>
            <ns2:element3>I want this text</ns2:element3>
        </ns2:element2>
    </element1>
</root_element >

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM