Performance-effective way to transform XML data represented as Writeable
I'm working on utility method that allows conversion of XML data into formatted String
and before you're going to think it's a trivial task for javax.xml.transform.Transformer
let me explain the specific constraints I've faced with.
The input data does not exist at the moment conversion starts. Actually it's represented as groovy.lang.Writeable
(javadoc) instance that I could output into any开发者_StackOverflow java.io.Writer
instance. Signature of method looks like this:
static String serializeToString(Writable source)
My current solution involves few steps and actually provides expected result:
- Create
StringWriter
, outputsource
there and convert toString
- Create
javax.xml.transform.stream.StreamSource
instance based on this string (usingStringReader
) - Create new
StringWriter
instance and wrap it intojavax.xml.transform.stream.StreamResult
- Perform transformation using instance of
javax.xml.transform.Transformer
- Convert
StringWriter
toString
While solution does work I'm not pleased enough with its efficiency. This method will be used really often and I do want to optimize it. What I'd like to avoid is necessity to perform multiple conversions along the line:
- From
Writeable
toString
(unformatted) - From
String
toStreamSource
(which means that data will be parsed again) - From
StreamSource
toString
again (formatted)
So the question is whether it's possible to build pipe-like flow which eliminates unnecessary conversions?
UPDATE #1:
To give a little bit more context, I'm converting GPathResult
instance to formatted string using StreamingMarkupBuilder.bindNode()
method which produces Writable
instance. Unfortunately there is no way to specify StreamingMarkupBuilder
to produce formatted output.
UPDATE #2:
I did experiment with implementation based on PipedWriter + PipedReader but experiments didn't show much speed gain from this approach. Looks like it's not that critical issue in this case.
Not knowing what you mean exactly by "XML data", but you could think of representing the "Yet-to-be" stuff as a SAXSource directly, thereby by-passing the "to-string" and "parse-string" steps.
精彩评论