gpt4 book ai didi

java - 将 xml 节点的所有内容作为字符串获取

转载 作者:搜寻专家 更新时间:2023-10-30 21:00:09 26 4
gpt4 key购买 nike

我正在使用这段代码来解析 xml

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(data));
Document doc = db.parse(is);

现在我想从一个 xml 节点中获取所有内容。喜欢来自这个 xml

<?xml version='1.0'?>
<type>
<human>
<Name>John Smith</Name>
<Address>1/3A South Garden</Address>
</human>
</type>

所以如果想得到<human>的所有内容作为文本。

<Name>John Smith</Name>
<Address>1/3A South Garden</Address>

我怎样才能得到它?

最佳答案

private String nodeToString(Node node) {
StringWriter sw = new StringWriter();
try {
Transformer t = TransformerFactory.newInstance().newTransformer();
t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
t.transform(new DOMSource(node), new StreamResult(sw));
} catch (TransformerException te) {
System.out.println("nodeToString Transformer Exception");
}
return sw.toString();
}

关于java - 将 xml 节点的所有内容作为字符串获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6534182/

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