...

View Full Version : DocumentBuilderFactory and TransformerFactory



otnj2ee
01-12-2008, 12:17 AM
I saw some coding like this:

factory = DocumentBuilderFactory.newInstance();
builder = factory.newDocumentBuilder();

Document doc = builder.newDocument();


ByteArrayOutputStream baos = new ByteArrayOutputStream();

TransformerFactory tf = TransformerFactory.newInstance();

Transformer t = tf.newTransformer();
t.setOutputProperty("encoding","UTF-8");

t.transform(new DOMSource(doc),new StreamResult(baos)); String xmlString = new String(baos.toByteArray(), "utf8");

My questions are:

1) Does the doc (Document)
contains the such header as:

<?xml version="1.0" ?>

2) Must the doc object host an XML string, or it can contain any type string(i.e., not necessarily an XML string)?

3) What is the purpose of using the transformer to transform the doc as:

t.transform(new DOMSource(*doc*),new StreamResult(*baos*));

4) Does the Transformer add the header <?xml version="1.0" ?> to the baos object?


Thanks


Scott

shyam
01-12-2008, 03:07 AM
1) Does the doc (Document)
contains the such header as:

<?xml version="1.0" ?>
thats the processing instruction that identifies that the content following is xml



2) Must the doc object host an XML string, or it can contain any type string(i.e., not necessarily an XML string)?
doc can hold any SGML content which means xml or html in the form of elements, attributes and text-nodes



3) What is the purpose of using the transformer to transform the doc as:

t.transform(new DOMSource(*doc*),new StreamResult(*baos*));
to print out the content of the xml document in doc


4) Does the Transformer add the header <?xml version="1.0" ?> to the baos object?
yes

otnj2ee
01-14-2008, 07:46 PM
Thanks for the response.

A further question (ajax RELATED):

I also saw some codes like this:

(I)

public void test(...){
...
t.transform(new DOMSource(doc),new StreamResult(baos));
//The transform(...) is the last line of the function
}


(II)

public void test(...){
...
t.transform(new DOMSource(doc),new StreamResult(baos));
String xmlString = new String(baos.toByteArray(), "utf8");

response.getOutputStream().println(xmlString);[/B]

//The .println(...) is the last line of the function
}


So, what is the difference between (I) and (II)? I mean in (I) the document is returned as a String via t.transform(new DOMSource(doc),new StreamResult(baos)); While in (II) the String is returned via response.getOutputStream().println(xmlString). Why so?



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum