[Date Prev]
| [Thread Prev]
| [Thread Next]
| [Date Next]
--
[Date Index]
| [Thread Index]
Re: [xml-dev] Best way to create an XML document
- From: "Mukul Gandhi" <gandhi.mukul@gmail.com>
- To: "Michael Glavassevich" <mrglavas@ca.ibm.com>
- Date: Sat, 12 Apr 2008 22:18:53 +0530
Thanks, Michael for your response (and, Andrew).
The following program worked:
import org.apache.xalan.processor.TransformerFactoryImpl;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;
import org.xml.sax.helpers.AttributesImpl;
public class MyXMLWriter {
public static void main(String[] args) {
try {
TransformerFactoryImpl tfi = new TransformerFactoryImpl();
TransformerHandler tHandler = tfi.newTransformerHandler();
tHandler.setResult(new StreamResult(System.out));
tHandler.startDocument();
tHandler.startElement("", "x", "x", null);
AttributesImpl attrs = new AttributesImpl();
attrs.addAttribute("", "attr1","attr1", "", "123");
attrs.addAttribute("", "attr2","attr2", "", "456");
tHandler.startElement("", "y", "y", attrs);
tHandler.startElement("", "z", "z", null);
tHandler.endElement("", "z", "z");
tHandler.endElement("", "y", "y");
tHandler.endElement("", "x", "x");
tHandler.endDocument();
}
catch(Exception ex) {
ex.printStackTrace();
}
}
}
This produces output (as I intended):
<?xml version="1.0" encoding="UTF-8"?><x><y attr1="123" attr2="456"><z/></y></x>
I have following follow-up questions, and would appreciate clearing my doubts:
1) Is it possible to pretty print the output?
2) Is this approach faster than using DOM serialization?
3) Here I am using the transformer functionality for creating XML,
which looks more like a XSLT feature (i.e., transformation task).
Should we not have this capability in the XML parser (for e.g., in
Xerces)? Should we have something like xml-writer (which Rob pointed)
built into Xerces (possibly as an enhancement)?
At the end of all this, it struck to me, I should try violating the
well-formedness constraint of XML and see what happens. And to my
surprise, this technique also suffers from the same problem I
mentioned with xml-writer. Why does the implementation doesn't ensure
this?
For e.g, I am able to produce this as well using this code:
<x><y attr1="123" attr2="456"><z/></y></t> (please note, a wrong tag
</t> here).
On Sat, Apr 12, 2008 at 8:09 PM, Michael Glavassevich
<mrglavas@ca.ibm.com> wrote:
> You haven't specified a target for the transformer to write to. Try setting
> one with TransformerHandler.setResult().
>
> Michael Glavassevich
> XML Parser Development
> IBM Toronto Lab
> E-mail: mrglavas@ca.ibm.com
> E-mail: mrglavas@apache.org
--
Regards,
Mukul Gandhi
[Date Prev]
| [Thread Prev]
| [Thread Next]
| [Date Next]
--
[Date Index]
| [Thread Index]