gpt4 book ai didi

java - 使用 XPATH Java 从 XML 字符串读取值

转载 作者:太空宇宙 更新时间:2023-11-04 12:49:24 24 4
gpt4 key购买 nike

我希望从 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> 内的值标签 - “这是我的内容”。

关于java - 使用 XPATH Java 从 XML 字符串读取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35987003/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com