Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert xml Element and its child nodes into String in Java?

Tags:

java

dom

string

xml

Hi I want to convert XML node and its child into a string with its node names.

For example I get a node from XML document which is look like this:

<Name>
  <Work>*86</Work>
  <Home>*86</Home>
  <Mobile>*80</Mobile> 
  <Work>0</Work>
</Name>

I want to convert whole node into string. With nodenames, not only text. Any help in this regards is greatly appreciated. Thanks.

like image 483
arsalan Avatar asked Mar 22 '11 11:03

arsalan


People also ask

How to appendChild node in existing xml file?

Add a Node - appendChild()The appendChild() method adds a child node to an existing node. The new node is added (appended) after any existing child nodes. Note: Use insertBefore() if the position of the node is important.


2 Answers

you can use JDom XMLOutputter subject to the condition that your Element is an org.jdom.Element:

XMLOutputter outp = new XMLOutputter();
String s = outp.outputString(your_jdom_element);
like image 175
felixsigl Avatar answered Oct 16 '22 18:10

felixsigl


You can use a transformer for that:

Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");

StreamResult result = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(node);
transformer.transform(source, result);

String xmlString = result.getWriter().toString();
System.out.println(xmlString);
like image 25
wjans Avatar answered Oct 16 '22 17:10

wjans