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– dash1e2012-04-22 10:13:39 +00:00Commented Apr 22, 2012 at 10:13
-
Generate an xml file from java.Jake Badlands– Jake Badlands2012-04-22 10:35:54 +00:00Commented Apr 22, 2012 at 10:35
-
1possible duplicate of Generating XML using SAX and Javasvick– svick2012-04-22 14:56:45 +00:00Commented Apr 22, 2012 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>
1 Comment
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());
2 Comments
<item id="2456"> <product>Head First Java</product> <price>250.0</price> <quantity>10</quantity> </item>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.