5

I need to generate XML and they differ only in the values, that the tags contain.

Is it possible to create a template XML and then write only the values each time? (I do not want to go the JAXB way as these are small XMLs and are not worth creating objects for them).

Is this a good approach?

Any thoughts?

imtheman
  • 4,713
  • 1
  • 30
  • 30
RJ.
  • 313
  • 2
  • 5
  • 14

3 Answers3

2

You can use freemarker or velocity for templating in java -- or even just add PHP tags to a sample XML to generate from a template.

I think as a general rule, though, once you start conditionally adding elements or attributes, or looping to generate multiples, you're better of generating your XML -- though I agree sometimes getting it into a format you want (not what the generator wants) is sometimes a pain.

fijiaaron
  • 5,015
  • 3
  • 35
  • 28
1

As long as the XML file to be produced is small, simple and mostly consistent in format, I tend to buck the trend: I simply create and write a text string.

writer.out.format("<?xml version='1.0'><root><tag1>%s</tag1></root>", value1)

kinda thing.

Carl Smotricz
  • 66,391
  • 18
  • 125
  • 167
  • Java doesn't stop you from doing this with a String of practically any length. For sanity's sake, though, I would set a limit at about 20 lines of output text, or perhaps 20 tags. – Carl Smotricz Nov 05 '09 at 12:21
  • FYI, the trend Carl mentions: http://stackoverflow.com/questions/3034611/whats-so-bad-about-building-xml-with-string-concatenation – Robert Fleming Sep 11 '13 at 19:41
0

Despite the fact that you are against jaxb (which I have yet to use), I wish to recommend a comparable way to do this with Apache's XMLBeans.

This requires you to use an xml schema - but from my experience it worth it...

Yaneeve
  • 4,751
  • 10
  • 49
  • 87
  • You can also generate an XML Schema from an example with XMLBeans using inst2xsd http://xmlbeans.apache.org/docs/2.0.0/guide/tools.html#inst2xsd – fijiaaron Feb 28 '12 at 14:45