我正在使用此代码来解析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>
我怎样才能得到它?
答案 0 :(得分:30)
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();
}