java - 关于使用 Java 的 XPath

标签 java xpath

我在通过使用 java.util.XPath 提供 XPath 来获取元素的值时遇到问题。我尝试了很多事情但都没有成功。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

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

import com.dell.logistics.framework.transform.NamespaceContext;

public class GetXPath {

    protected Object evaluate(String xpathStr, String xml, String namespaces) throws XPathExpressionException {
        InputSource inputSource = new InputSource(new StringReader(xml));
        XPathFactory factory = XPathFactory.newInstance();
        XPath xPath = factory.newXPath();
        NamespaceContext nsContext = new NamespaceContext();
        nsContext.setNamespacesMap(getNsMap(namespaces));
            //System.out.println(nsContext.getPrefix(namespaces));
        xPath.setNamespaceContext(nsContext);
        XPathExpression xpExp = xPath.compile(xpathStr);
        return xpExp.evaluate(inputSource, XPathConstants.NODESET);
    }

    private Map<String, String> getNsMap(String namespaces) {

        String delims = ",";
        String[] nsKeyValue = namespaces.split(delims);
        Map<String, String> mp = new HashMap<String, String>();
        for (String string : nsKeyValue) {
            mp.put(string.split("=")[0], string.split("=")[1]);
            System.out.println(string.split("=")[0] + string.split("=")[1]);
        }
       return mp;
    }

    public static String readFile(String fileName) {
        try {
        //    InputStream is = null;
              InputStream is = GetWorkOrderDataExtractor.class.getResourceAsStream(fileName);
              BufferedReader br = new BufferedReader(new InputStreamReader(is));
              StringBuffer sb = new StringBuffer();
              String l = null;
              while ((l = br.readLine()) != null) {
                    sb.append(l).append("\n");
              }
              return sb.toString();
        } catch (Exception e) {
              e.printStackTrace();
        }
        return null;
  }


    public static void main(String[] args) 
   throws ParserConfigurationException, SAXException, 
          IOException, XPathExpressionException {
        GetXPath g = new GetXPath();
        String xml = readFile("fooewo.xml");
        String value = null;
        System.out.println(xml);


        NodeList containerNodes = (NodeList) g.evaluate(
                "/demo",xml,
                "a=http://schemas.demo.com/it/WorkOrderChannelAckNackResponse/1.0");

        try{
        for (int i = 0; i < containerNodes.getLength(); i++) {

                // get the node value.
                value = containerNodes.item(i).getTextContent();
                System.out.println(value);
            }
        System.out.println("Node Found : " + containerNodes.getLength() + " times");
        } 
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}
"

XML 文件:

    <?xml version="1.0" encoding="utf-8"?>
<demo xmlns="try with ur schema">
    <test>
        <value>10</value>
        <color>red</color>
        <animal>dog</animal>
        <day>13</day>
        <age>22</age>
    </test>
    <test>
        <value>20</value>
        <color>green</color>
        <animal>cat</animal>
        <day>12</day>
        <age>23</age>
    </test>
</demo>

感谢任何帮助。

谢谢,
普拉迪普

最佳答案

我认为轻松评估 XPath 的最佳方法是使用 AXIOMXPath

这是一个例子,

OMElement documentElement = new StAXOMBuilder(inStreamToXML).getDocumentElement();
AXIOMXPath xpathExpression = new AXIOMXPath ("/demo");  
List nodeList = (OMNode)xpathExpression.selectNodes(documentElement); 

通过遍历列表就可以轻松得到结果。

关于java - 关于使用 Java 的 XPath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9696424/

相关文章:

java - 如何在 Selenium 中为下面的 span 类编写 XPATH?

html - 用于 Xml 到表转换的 XSL

java - 从领域对象构建DTO的设计

java - Spring hibernate关于延迟加载的错误

java - 哪个类是所有类的父类(super class)

c# - "Expression must evaluate to a node-set."

xml - 如何使用 XSL 中的每个组

xml - XPath 获取除具有特定名称的子元素之外的所有子元素?

java - 覆盖字段初始化

java - 在 AWS 上的 H2o.AI 中构建模型抛出内存不足错误