关于使用Java的XPath

时间:2012-03-14 05:28:28

标签: java xpath

通过使用java提供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>

任何帮助表示感谢。

谢谢,
普拉迪普

1 个答案:

答案 0 :(得分:0)

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

这是一个例子,

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

通过遍历列表,您可以轻松获得结果。