How to inject raw XML string into an XML output
843834Jan 17 2010 — edited Jan 22 2010Hi all,
I need to translate an XML proprietary file into an XMI file. Basically, the original file looks like:
<p>
..<c>
*....<d>*
*......<e>*
*......</e>*
*....</d>*
..</c>
</p>
and the result should be something like:
<p1>
..<c1>
..</c1>
*....<d1>*
*......<e1>*
*......</e1>*
*....</d1>*
</p1>
<p1> contents being merely similar to <p> with some changes in the attributes, same for <c1>, <d1>, <e1> ...
To get the transformation I use a TransformHandler. When I reach <c>, I create an auxilliary TranformHandler which uses a buffer as an output. I use it to generate in this buffer:
....<d1>
......<e1>
......</e1>
....</d1>
When I reach the end of <c>, I complete the <c1> element and I thought I would only have to "dump" the buffer in the main TransformHandler and to carry on.
I use the "characters" method but the problem is that all the tags from the buffer are modified using <, > instead of "<" and ">" in the output !
So my question is "how is it possible to inject plain xml syntax in the output of a TransformHandler" ??
The code below illustrates the problem:
ByteArrayOutputStream out = new ByteArrayOutputStream();
SAXTransformerFactory stf = (SAXTransformerFactory)
SAXTransformerFactory.newInstance();
TransformerHandler th = stf.newTransformerHandler();
th.getTransformer().setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
th.getTransformer().setOutputProperty(OutputKeys.INDENT, "yes");
th.setResult(new StreamResult(out));
th.startDocument();
th.getTransformer().setOutputProperty(OutputKeys.METHOD, "xml");
th.startElement("", "foo", "foo", new AttributesImpl());
// in the real program, this buffer is built by an auxilliary TransformHandler
char buffer[] = "<hello></hello>".toCharArray();
th.characters(buffer, 0, buffer.length);
th.endElement("", "foo", "foo");
th.endDocument();
System.out.println("out is: " + out.toString());
=> <foo><hello></hello></foo>
I expected:
<foo>
<hello></hello>
</foo>
Note: I tried to change the "METHOD" property to "text" before calling "characters" but it does not work. It seems it is not possible to change the METHOD property during the transformation process.
Please help !
-- Olivier