java-以字符串形式获取xml节点的所有内容

我正在使用此代码来解析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节点的所有内容 的全部内容, 来源链接: utcz.com/qa/414405.html

回到顶部