Please, tell me, how to generate XML in Java? I couldn't find any example using SAX framework.
-
1What do you need? Read an xml file from java or generate an xml file from java? – dash1e Apr 22 '12 at 10:13
-
Generate an xml file from java. – Jake Badlands Apr 22 '12 at 10:35
-
1possible duplicate of [Generating XML using SAX and Java](http://stackoverflow.com/questions/4898590/generating-xml-using-sax-and-java) – svick Apr 22 '12 at 14:56
6 Answers
Try Xembly, a small open source library that wraps native Java DOM with a "fluent" interface:
String xml = new Xembler(
new Directives()
.add("root")
.add("order")
.attr("id", "553")
.set("$140.00")
).xml();
Will generate:
<root>
<order id="553">$140.00</order>
</root>

- 102,010
- 123
- 446
- 597
-
Thank you for reply. Although this is not a built-in library, interesting advice. – Jake Badlands Oct 24 '13 at 11:13
SAX is a library to parse existing XML files with Java. It is not to create a new XML file out of Java. If you want to do this use a library like DOM4J to create a XML tree and then write it to a file.

- 30,811
- 12
- 60
- 80
See this, this, Generating XML using SAX and Java and this

- 1
- 1

- 6,149
- 1
- 23
- 38
You can also use libraries like JAXB or SimpleXML or XStream if you want to easily map/convert your java objects to XML.
Say we have a simple entity/pojo - Item.The properties of the pojo class can be made the XML's element or attribute with simple annotations.
@Entity @Root public class Item {
@Attribute
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
@Transient
@ManyToOne
private Order order;
@Element
private String product;
@Element
private double price;
@Element
private int quantity; }
To generate XML from this item, the code can be simply
Serializer serializer=new Persister();//SimpleXML serializer
Item itemToSerializeToXml=new Item(2456L, "Head First Java", 250.00,10);//Object to be serialized
StringWriter destinationXMLWriter=new StringWriter();//Destination of XML
serializer.write(itemToSerializeToXml,destinationXMLWriter);//Call to serialize the POJO to XML
System.out.println(destinationXMLWriter.toString());

- 3,069
- 1
- 24
- 34
I found a nice library for XML creation on GitHub at https://github.com/jmurty/java-xmlbuilder . Really good for simple documents at least (I didn't have an opportunity to employ it for anything bigger than around a dozen lines).
The good thing about this library is that each of its commands (i.e. create attribute, create element, etc.) has 3 levels of abbreviations. For example, to add the tag <foo>
to the document you can use the following methods:
.e("foo")
(single-letter form).elem("foo"
(4 letter form).element("foo")
(fully spelled-out form)
This allows creating XML using both longer and more abbreviated code, as appropriate, so it can be a good fit for a variety of coding styles.

- 231
- 2
- 7