gpt4 book ai didi

java - 如何在 Java 中解析包含 XML 的字符串并检索根节点的值?

转载 作者:IT老高 更新时间:2023-10-28 20:54:30 24 4
gpt4 key购买 nike

我有一个包含

的字符串形式的 XML
<message>HELLO!</message> 

我怎样才能得到字符串“你好!”来自 XML?这应该很容易,但我迷路了。 XML 不在文档中,它只是一个字符串。

最佳答案

使用 JDOM :

String xml = "<message>HELLO!</message>";
org.jdom.input.SAXBuilder saxBuilder = new SAXBuilder();
try {
org.jdom.Document doc = saxBuilder.build(new StringReader(xml));
String message = doc.getRootElement().getText();
System.out.println(message);
} catch (JDOMException e) {
// handle JDOMException
} catch (IOException e) {
// handle IOException
}

使用 Xerces DOMParser:

String xml = "<message>HELLO!</message>";
DOMParser parser = new DOMParser();
try {
parser.parse(new InputSource(new java.io.StringReader(xml)));
Document doc = parser.getDocument();
String message = doc.getDocumentElement().getTextContent();
System.out.println(message);
} catch (SAXException e) {
// handle SAXException
} catch (IOException e) {
// handle IOException
}

使用 JAXP 接口(interface):

String xml = "<message>HELLO!</message>";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = null;
try {
db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
try {
Document doc = db.parse(is);
String message = doc.getDocumentElement().getTextContent();
System.out.println(message);
} catch (SAXException e) {
// handle SAXException
} catch (IOException e) {
// handle IOException
}
} catch (ParserConfigurationException e1) {
// handle ParserConfigurationException
}

关于java - 如何在 Java 中解析包含 XML 的字符串并检索根节点的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8408504/

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