gpt4 book ai didi

java - 如何使用java从下面的xml代码中提取值?

转载 作者:行者123 更新时间:2023-11-30 03:54:45 25 4
gpt4 key购买 nike

如何使用java从下面的xml代码中提取值?这里我想使用java提取to、from、body、thread值。这里总代码被视为字符串。

<message to="-105608156545@chat.facebook.com/Smack" 
from="-105465454665906545@chat.facebook.com"
type="chat">
<body>sai</body>
<thread>NNLWF1</thread>
<active xmlns="http://jabber.org/protocol/chatstates" />
</message>

最佳答案

一种可能性是在内置 XPath 功能中使用 Java,例如...

try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(new File("Test.xml"));

XPath xPath = XPathFactory.newInstance().newXPath();
XPathExpression expression = xPath.compile("/message[@from]");
Node node = (Node)expression.evaluate(document, XPathConstants.NODE);
System.out.println("From: " + node.getAttributes().getNamedItem("from").getNodeValue());

expression = xPath.compile("/message/body");
node = (Node)expression.evaluate(document, XPathConstants.NODE);
System.out.println("Body: " + node.getTextContent());

expression = xPath.compile("/message/thread");
node = (Node)expression.evaluate(document, XPathConstants.NODE);
System.out.println("Thread: " + node.getTextContent());
} catch (ParserConfigurationException | SAXException | IOException | DOMException | XPathExpressionException exp) {
exp.printStackTrace();
}

哪个输出...

From: -105465454665906545@chat.facebook.com
Body: sai
Thread: NNLWF1

看一下:

了解更多详情

关于java - 如何使用java从下面的xml代码中提取值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23509480/

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