java - Getting all content of a xml node as string
I am using this code to parsing xml
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(data));
Document doc = db.parse(is);
Now I want to get all content from a xml node. Like from this xml
<?xml version='1.0'?>开发者_开发知识库
<type>
<human>
<Name>John Smith</Name>
<Address>1/3A South Garden</Address>
</human>
</type>
So if want to get all content of <human>
as text.
<Name>John Smith</Name> <Address>1/3A South Garden</Address>
How can I get it ?
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();
}
精彩评论