Skip to main content

org.w3c.dom parse xml string?

3 replies [Last post]
jeremygwa
Offline
Joined: 2006-01-17

hi all,

I have been studying the org.w3c.dom package documentation.

What i want to do is to parse a block of xml text retrieved from a socket. so far, I can only seem to find methods to read xml files.....how do i read and process a string of xml?

Thanks in advance for all help.

-Jer

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
samelzoro
Offline
Joined: 2007-12-18

/*
* Main.java
*

*/

import java.io.*;
import org.w3c.dom.*;
import org.xml.sax.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;

public class Main {

/** Creates a new instance of Main */
public Main() {
}

public static void main(String[] args) {
String xmlText="";
xmlText+="Child1Child2";
try {
// Create a factory
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// Use document builder factory
DocumentBuilder builder = factory.newDocumentBuilder();
//Parse the document
[b]Reader reader=new CharArrayReader(xmlText.toCharArray());
Document doc = builder.parse(new org.xml.sax.InputSource(reader)); [/b]

TransformerFactory tranFact = TransformerFactory.newInstance();
Transformer transfor = tranFact.newTransformer();
Node node =doc.getDocumentElement();
Source src = new DOMSource(node);
Result dest = new StreamResult(System.out);
transfor.transform(src, dest);
}
catch (Exception e) {
System.err.println(e);
}
}

}

Message was edited by: samelzoro

cbrevard
Offline
Joined: 2010-07-06

Thank you so much for this example.

I was having difficulty understanding why the parser was failing despite the fact that I had provided a ByteStream created with a specified character set (via String's getBytes("charset name"))

sandoz
Offline
Joined: 2003-06-20

See the javax.xml.parsers package and the DocumentBuilderFactory and DocumentBuilder classes, and more specifically the DocumentBuilder.parse methods.

Also, you may find this link useful:

http://xerces.apache.org/xerces2-j/faq-dom.html

Paul.