- How to create XML programmatically in java / How to create XML using DOM parser in java / How to create XML file from java program
- Generate XML Schema from Java class using ‘schemagen’ tool
- What is an XML schema?
- ‘schemagen’ Command Line Options
- Create required Java files
- Employee.java
- Address.java
- ‘schemagen’ command for schema genearation
How to create XML programmatically in java / How to create XML using DOM parser in java / How to create XML file from java program
Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home3/codippac/public_html/wp-content/plugins/wp-syntax/wp-syntax.php on line 380
XML stands for eXtended Markup Language and is a widely used standard for transmitting information across systems mainly due to the flexibility it provides in creating the structure and data it can contain. That is, application developers can create their own structure which suits their application as there are no pre-defined tags in XML. Scenario Since it is a widely used standard, there arises a vital requirement to create an XML document either in the form of a String or a physical file from java application. Practical scenario is when data of one component of your application data is stored in a database table and you want to make it available to some other application or for some other component of your application which is separate from this component and you cannot share the database details with either of them. The solution is you create an XML out of table data and share it with any component.
Create XML from Java Program using DOM Parser Given below is a sample XML structure which we will be creating from java program. The structure is simple but enough for learning purpose and you can create more complex structure if you know how things work.
The XML has a root tag with name Users and has child tags for each user details. A user tag is named as User which has user name in a child tag. Each user tag also has an id attribute. Code to create above XML is given below followed by a detailed explanation of the same.
import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Element; public static void main(String[] args) throws ParserConfigurationException, TransformerException { DocumentBuilder builder = null; try { builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); } catch (ParserConfigurationException e) { throw e; } Document document = builder.newDocument(); // create root element Element root = document.createElement("Users"); // attach it to the document document.appendChild(root); // create user node Element user = document.createElement("User"); // create its id attribute user.setAttribute("id", "2"); // add user node to root node root.appendChild(user); // create name node and set its value Element userName = document.createElement("name"); userName.setTextContent("codippa"); // attach this node to user node user.appendChild(userName); // write xml Transformer transformer; try { TransformerFactory transformerFactory = TransformerFactory .newInstance(); transformer = transformerFactory.newTransformer(); Result output = new StreamResult(new File("codippa.xml")); Source input = new DOMSource(document); // if you want xml to be properly formatted transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.transform(input, output); } catch (TransformerConfigurationException e) { throw e; } catch (TransformerException e) { throw e; } }
Details :
At first step, create a org.w3c.Document object. This object is a handle to the XML file. Next we need to create individual nodes as required by the XML structure. In every XML, the first node is the root node which contains all other nodes. Hence, we first create a root node. A node is created using createElement() method of org.w3c.Document . Method of creating a node is the same, whether it is a root node or a child node. The only difference what makes a node as root or child is the node to which we attach the newly created node.
For Example, we get a node using createElement() method. Let’s name it as node1. Now if we attach it to the document object, then it becomes the root node. If we attach it to another node, say node2, then node1 becomes the child of node2. For creating an attribute of a node (such as id attribute in ), call setAtrribute() method on a node. This method takes two arguments, attribute name and its value. A node is attached using appendChild() method. For creating multiple nodes inside a node, such as , nodes inside node, create three nodes, one of User and the other two of name and country. Attach name and country nodes to the User node (using appendChild() method off course) and attach User node to the root node.
In this way multiple nodes can be created and attached to the root or to another node (for creating child nodes).
- Besides using setAttribute() method directly on a node, an attribute can also be created using below code
// create an attribute with given name Attr attr = document.createAttribute("id"); // set its value attr.setValue("1"); // attach it to desired node user.setAttributeNode(attr);
// this will write to a file Result output = new StreamResult(new File("codippa.xml")); // this will print to console Result output = new StreamResult(System.out);
Did this post help you solve a problem? Wonderful . Keep visiting for more solutions…
Generate XML Schema from Java class using ‘schemagen’ tool
Java Architecture for XML Binding (JAXB) allows Java developers to map Java classes to XML representations. JAXB provides two main features: the ability to marshal Java objects into XML and the inverse, i.e. to unmarshal XML back into Java objects.
JAXB provides “xjc” tool to convert XML Schema to class representations. In addition, JAXB includes a “schemagen” tool which can essentially perform the inverse of “xjc”, creating an XML Schema from a set of annotated classes.
In this example, we will see how to generate XML schema from Java class using schemagen tool from command line.
What is an XML schema?
XML schema describes the structure of the data elements and their relationships in an XML document. XML schema can be written using Document Type Definition (DTD), XML Schema Language, and RELAX NG. Previous versions of JAXB reference implementation worked with only DTD and the latest versions uses XML Schema Language. The XML Schema language can also be referred as XML Schema Definition (XSD). We can create many XML document from a XML schema. For easy understanding we can say that,
XML schema ⇔ Java class.
With one Java class, we can create many objects similarly with one XML schema we can create many XML documents.
We use the Java Architecture for XML Binding (JAXB) schema generator tool, schemagen, to generate a XML schema from Java source files or class files.
Process | JDK Tool |
---|---|
From Java source file -> XML schema | schemagen |
‘schemagen’ Command Line Options
We are going to generate a XML schema for a XML document shown below.
Kumar 30000.0 Junior Developer Chennai 242 Main Street TN 600001
Create required Java files
We create two Java classes Employee and Address with proper JAXB annotations set as follows.
Employee.java
package com.theopentutorials.jaxb.beans; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; @XmlAccessorType(XmlAccessType.FIELD) @XmlRootElement(name = "employee") public class Employee < @XmlAttribute private int id; private String name; private double salary; private String designation; private Address address; public int getId() < return id; >public void setId(int id) < this.id = id; >public String getName() < return name; >public void setName(String name) < this.name = name; >public double getSalary() < return salary; >public void setSalary(double salary) < this.salary = salary; >public String getDesignation() < return designation; >public void setDesignation(String designation) < this.designation = designation; >public Address getAddress() < return address; >public void setAddress(Address address) < this.address = address; >>
Address.java
package com.theopentutorials.jaxb.beans; public class Address < private String line1; private String line2; private String city; private String state; private long zipcode; public String getLine1() < return line1; >public void setLine1(String line1) < this.line1 = line1; >public String getLine2() < return line2; >public void setLine2(String line2) < this.line2 = line2; >public String getCity() < return city; >public void setCity(String city) < this.city = city; >public String getState() < return state; >public void setState(String state) < this.state = state; >public long getZipcode() < return zipcode; >public void setZipcode(long zipcode) < this.zipcode = zipcode; >>
‘schemagen’ command for schema genearation
In Windows open Command Prompt (Windows button + R and type cmd) or Terminal in Linux and go to the folder (use cd command) where your java code exists.
- Compile the above Java classes and place the classes in ‘bin’ folder. Type the following command,
C:\Users\iByteCode\Desktop\JAXBCodes\JAXBSchemaGen>javac -d bin src\com\theopentutorials\jaxb\beans\*.java
C:\Users\iByteCode\Desktop\JAXBCodes\JAXBSchemaGen>schemagen -cp bin src\com\theopentutorials\jaxb\beans\Employee.java