Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to convert Nodelist to a String using JAVA

 
Krysty Sullivan
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How do I convert a NodeList to its corresponding XML String using JAVA ?
[ August 19, 2002: Message edited by: Krysty Sullivan ]
 
Selin Ebeci
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

You can only convert a Node object to an XML string due to the fact that the root element must be well-formed. Anyway you can convert NodeList object to a Node easily, check this out... :

/* To read xml string*/
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xmlString));
Document doc = db.parse(is);

/* Create a sub xml starts with given tag name soaphead*/
NodeList soaphead = doc.getElementsByTagName("soaphead");
StringWriter sw = new StringWriter();
Transformer serializer = TransformerFactory.newInstance().newTransformer();
serializer.transform(new DOMSource(soaphead.item(0)), new StreamResult(sw));
String result = sw.toString();

Cheers,
Selin Ebeci
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic