woodhead92
woodhead92

Reputation: 117

Creating an XML document using Java

I have seen many programs where XML documents can be created using Java with specified fields. I am yet to come across one where the user gets to decide the names of the rootElement's and the childEelement's. Does anyone know how to go about this?

Upvotes: 0

Views: 276

Answers (3)

zawhtut
zawhtut

Reputation: 8561

Use XStream

Java Code

XStream xstream = new XStream();
xstream.alias("person", Person.class);
xstream.alias("phonenumber", PhoneNumber.class);

Person joe = new Person("Joe", "Walnes");
joe.setPhone(new PhoneNumber(123, "1234-456"));
joe.setFax(new PhoneNumber(123, "9999-999"));

String xml = xstream.toXML(joe);

Output XML

<person>
  <firstname>Joe</firstname>
  <lastname>Walnes</lastname>
  <phone>
    <code>123</code>
    <number>1234-456</number>
  </phone>
  <fax>
    <code>123</code>
    <number>9999-999</number>
  </fax>
</person>

Library: http://x-stream.github.io/tutorial.html

Upvotes: 3

Java Man
Java Man

Reputation: 1860

Check out this example you can get xml at the end of example using JDOM parser .

Creating an XML document using Java

JDOM example to create XML file.

import java.io.FileWriter;
import java.io.IOException;
import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

public class WriteXMLFile {
    public static void main(String[] args) {

      try {

        Element company = new Element("company");
        Document doc = new Document(company);
        doc.setRootElement(company);

        Element staff = new Element("staff");
        staff.setAttribute(new Attribute("id", "1"));
        staff.addContent(new Element("firstname").setText("yong"));
        staff.addContent(new Element("lastname").setText("mook kim"));
        staff.addContent(new Element("nickname").setText("mkyong"));
        staff.addContent(new Element("salary").setText("199999"));

        doc.getRootElement().addContent(staff);

        Element staff2 = new Element("staff");
        staff2.setAttribute(new Attribute("id", "2"));
        staff2.addContent(new Element("firstname").setText("low"));
        staff2.addContent(new Element("lastname").setText("yin fong"));
        staff2.addContent(new Element("nickname").setText("fong fong"));
        staff2.addContent(new Element("salary").setText("188888"));

        doc.getRootElement().addContent(staff2);

        // new XMLOutputter().output(doc, System.out);
        XMLOutputter xmlOutput = new XMLOutputter();

        // display nice nice
        xmlOutput.setFormat(Format.getPrettyFormat());
        xmlOutput.output(doc, new FileWriter("c:\\file.xml"));

        System.out.println("File Saved!");
      } catch (IOException io) {
        System.out.println(io.getMessage());
      }
    }
}

Created XML File is below.

<?xml version="1.0" encoding="UTF-8"?>
<company>
  <staff id="1">
    <firstname>yong</firstname>
    <lastname>mook kim</lastname>
    <nickname>mkyong</nickname>
    <salary>199999</salary>
  </staff>
  <staff id="2">
    <firstname>low</firstname>
    <lastname>yin fong</lastname>
    <nickname>fong fong</nickname>
    <salary>188888</salary>
  </staff>
</company>

Thanks..

Upvotes: 1

wumpz
wumpz

Reputation: 9201

Here is an example how to do this. Surely there are more methods to achieve it. This one is using JAXB. (Java XML Binding)

http://www.mkyong.com/java/jaxb-hello-world-example/

This is now a very simple example. JAXB is nice because you annotate your pojos using standard Java:

import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class SimpleXML {
    String name;
    int id;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public static void main(String args[]) throws JAXBException {
        File xmlFile = new File("C:/temp/test.xml");

        SimpleXML xml = new SimpleXML();
        xml.setId(4);
        xml.setName("TestName");

        JAXBContext context = JAXBContext.newInstance(SimpleXML.class);
        Unmarshaller unmarshaller = context.createUnmarshaller();
        Marshaller marshaller = context.createMarshaller();

        //write to file
        marshaller.marshal(xml, xmlFile);

        //read from file
        SimpleXML newXML=(SimpleXML)unmarshaller.unmarshal(xmlFile);

        System.out.println(newXML.id);
        System.out.println(newXML.name);
    }    
}

This exmaple creates an instance of SimpleXML and writes this out in a file. This file looks like:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<simpleXML><id>4</id><name>TestName</name></simpleXML>

After that the file is read in again in another instance of SimpleXML. All values are preserved.

JAXB gives you much possibilities to tweak your XML output (tag names, attribute names, data converter and stuff).

Upvotes: 0

Related Questions