How to convert xml Element and its child nodes into String in Java?
41,437
Solution 1
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);
Solution 2
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);
Related videos on Youtube
Author by
arsalan
Updated on September 05, 2020Comments
-
arsalan over 3 years
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.
-
Suraj Chandran about 13 yearshow can you xml document look like *86 *86 *86 0 ? i am missing something
-
Suresh Kumar about 13 yearsIt will be easier to answer if you post the code
-
arsalan about 13 yearsNode node = doc.getElementBytagName("Name").item(0); i want the whole node in string is that achievable.or not.
-
Suresh Kumar about 13 years
-
-
arsalan about 13 yearsim working on android 2.0 in which Transformer clases are not available,there is any another way?