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 ?
public abstract class DocumentBuilder extends Object. Defines the API to obtain DOM Document instances from an XML document. Using this class, an application programmer can obtain a Document from XML. An instance of this class can be obtained from the DocumentBuilderFactory.
Document Object Model (DOM) is a standard tree structure, where each node contains one of the components from an XML structure. Element nodes and text nodes are the two most common types of nodes. With DOM functions we can create nodes, remove nodes, change their contents, and traverse the node hierarchy.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With