使用XPATH Java从XML String读取值

时间:2016-03-14 12:01:16

标签: java xpath

我希望从XML中检索Body元素的值。虽然我已经完成了正确的代码,但由于某些原因我得到了NULL指针异常。感谢任何帮助。

 package com.company;      
 import javax.xml.parsers.DocumentBuilder;
 import javax.xml.parsers.DocumentBuilderFactory;
 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.DOMException;
 import org.w3c.dom.Document;
 import org.w3c.dom.Node;
 import org.w3c.dom.NodeList;
 import org.xml.sax.InputSource;
 import org.xml.sax.SAXException;
 import java.io.File;
 import java.io.IOException;
 import java.io.StringBufferInputStream;
 import java.io.StringReader;

 public class Main {

 public static void main(String[] args)  {

   String xmlDoc = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Body>This is my content</Body>";

  try {
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    Document document = documentBuilder.parse(new InputSource(new StringReader(xmlDoc)));

    XPath xPath = XPathFactory.newInstance().newXPath();
    XPathExpression expression = xPath.compile("/Body");
    Node node = (Node) expression.evaluate(document, XPathConstants.NODE);
    System.out.println("Body: " + node.getAttributes().getNamedItem("Body").getNodeValue());           
       } 

  catch (ParserConfigurationException | SAXException | IOException | DOMException | XPathExpressionException exp) 
  {
      exp.printStackTrace();
     }
   }
 }

2 个答案:

答案 0 :(得分:0)

使用Node node = (Node) expression.evaluate(document, XPathConstants.NODE); System.out.println(node.getTextContent());。但显然你不需要XPath并且可以直接执行document.getDocumentElement().getTextContent()。另请注意,对于XPath,通常建议使用名称空间感知文档构建器。

答案 1 :(得分:0)

试试这个:)

 String xmlDoc = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Body>This is my content</Body>";
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        String value = builder.parse(new InputSource(new ByteArrayInputStream(xmlDoc.getBytes())))
                .getDocumentElement().getTextContent();

它返回<Body>标记内的值 - &#34;这是我的内容&#34;。