Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java - Getting all content of a xml node as string

Tags:

java

xml

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 ?

like image 649
Barun Avatar asked Jun 30 '11 11:06

Barun


People also ask

What is DocumentBuilder in Java?

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.

What is DOM element in Java?

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.


1 Answers

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();
}
like image 136
Rupok Avatar answered Sep 29 '22 03:09

Rupok