3

Please, tell me, how to generate XML in Java? I couldn't find any example using SAX framework.

Jake Badlands
  • 1,016
  • 3
  • 23
  • 46

6 Answers6

2

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>
yegor256
  • 102,010
  • 123
  • 446
  • 597
1

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.

Thomas Uhrig
  • 30,811
  • 12
  • 60
  • 80
1

See this, this, Generating XML using SAX and Java and this

Community
  • 1
  • 1
Tejas Patil
  • 6,149
  • 1
  • 23
  • 38
1

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()); 
Ahamed Mustafa M
  • 3,069
  • 1
  • 24
  • 34
1

use dom4j, here is quick start for dom4j

dom4j guide

Nurlan
  • 673
  • 4
  • 18
1

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.

Pabru
  • 231
  • 2
  • 7