Java - Geting все содержимое xml node как строка
Я использую этот код для разбора xml
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(data));
Document doc = db.parse(is);
Теперь я хочу получить весь контент из xml node.
Как из этого 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>
Как я могу его получить?
Ответы
Ответ 1
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();
}