20

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.

4
  • how can you xml document look like *86 *86 *86 0 ? i am missing something Commented Mar 22, 2011 at 11:25
  • It will be easier to answer if you post the code Commented Mar 22, 2011 at 11:26
  • Node node = doc.getElementBytagName("Name").item(0); i want the whole node in string is that achievable.or not. Commented Mar 22, 2011 at 11:30
  • see projectwownow.blogspot.com/2008/08/… Commented Mar 22, 2011 at 11:44

2 Answers 2

34

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);
Sign up to request clarification or add additional context in comments.

Comments

28

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);

1 Comment

im working on android 2.0 in which Transformer clases are not available,there is any another way?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.