使用xpath从java中的多个命名空间的xml文件中提取值

时间:2016-03-16 15:34:48

标签: java xml xpath

我试图在java中提取具有多个名称空间的节点值但不成功。 xml文件类似于:

<ns26:start xmlns:ns26="http://www.tektronix.com/iris/isa/capture/start"  
            xmlns:ns31="http://www.tektronix.com/iris/isa/filters"            
            xmlns:ns13="http://www.tektronix.com/iris/isa/monitoredObjects"  
            xmlns:ns6="http://www.tektronix.com/iris/isa"  
            xmlns:ns10="http://www.tektronix.com/iris/isa/monNodeObjects" 
            xmlns:ns7="http://www.tektronix.com/iris/isa/capture/monitoredElements" 
            xmlns:ns11="http://www.tektronix.com/iris/isa/pointcodes" 
            xmlns:ns8="http://www.tektronix.com/iris/isa/capture/captureSession" 
            xmlns:ns2="http://www.tektronix.com/iris/isa/sessionSaveInfo" 
            xmlns:ns4="http://www.tektronix.com/iris/isa/customData" 
            xmlns:ns3="http://www.tektronix.com/iris/isa/manifest">
    <ns6:Id>LAB:11300/isaclient;440</ns6:Id>
</ns26:start>

我想用xpath local-name()提取Id。表达式如//*[local-name()='start']/*[local-name()='Id']但未获得任何匹配的节点。请帮忙找到问题。感谢

在此处添加java代码:

public static List<String> getXPathValueNamespace(String xml, String expression throws ParserConfigurationException, SAXException, IOException, XPathExpressionException 
{
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    factory.setNamespaceAware(true);

    DocumentBuilder builder;

    Document doc = null;

    List<String> list = new ArrayList<String>();

    builder = factory.newDocumentBuilder();
    InputSource source = new InputSource(new StringReader(xml));

    doc = builder.parse(source);

    // Create XPathFactory object
    XPathFactory xpathFactory = XPathFactory.newInstance();

    // Create XPath object
    XPath xpath = xpathFactory.newXPath();
    XPathExpression expr = xpath.compile(expression);
    NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
    for (int i = 0; i < nodes.getLength(); i++)
        list.add(nodes.item(i).getNodeValue());

    return list;
}

1 个答案:

答案 0 :(得分:0)

表达式//*[local-name()='start']/*[local-name()='Id']有效,对于示例文档,结果节点列表中应包含一个节点。

但是您应该使用nodes.item(i).getTextContent()来检索节点内容,因为getNodeValue()会为元素节点返回null