我正在寻找从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();
     }
   }
 }

最佳答案

尝试这个 :)

 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>标记内返回值-“这是我的内容”。

09-28 02:36