9

I want to make a java swing application from where i can generated xml file which hold same data,and generated number of file will be decided by user.My xml file holds xml schema and my xml file struture is looking like this

<transaction>
  <xs:schema id="transaction" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
    <xs:element name="transaction" msdata:IsDataSet="true" msdata:UseCurrentLocale="true">
      <xs:complexType>
        <xs:choice minOccurs="0" maxOccurs="unbounded">
          <xs:element name="id">
            <xs:complexType>
              <xs:sequence>
                <xs:element name="name" type="xs:string" minOccurs="0" />
                <xs:element name="sn" type="xs:string" minOccurs="0" />
              </xs:sequence>
            </xs:complexType>
          </xs:element>
          <xs:element name="data">
            <xs:complexType>
              <xs:sequence>
                <xs:element name="dateTime" type="xs:dateTime" minOccurs="0" />
                <xs:element name="key" type="xs:string" minOccurs="0" />
              </xs:sequence>
            </xs:complexType>
          </xs:element>
          <xs:element name="productData">
            <xs:complexType>
              <xs:sequence>
                <xs:element name="dateTime" type="xs:dateTime" minOccurs="0" />
                <xs:element name="key" type="xs:string" minOccurs="0" />
              </xs:sequence>
            </xs:complexType>
          </xs:element>
        </xs:choice>
      </xs:complexType>
    </xs:element>
  </xs:schema>
  <id>
    <name>smith</tli>
    <sn>1234567</sn>
  </id>
  <data>
    <dateTime>2011-06-24T17:08:36.3727674+05:30</dateTime>
    <key>book</key>
  </data>
  <productData>
    <dateTime>2011-06-24T17:08:36.3727674+05:30</dateTime>
    <key>game</key>
  </productData>
</transaction>

I am new in java if some one give some code snipes help, it will be more helpful for me.

I want to generate xml files which hold the xml schema which is given in my example xml.

javanna
  • 59,145
  • 14
  • 144
  • 125
saba
  • 539
  • 1
  • 14
  • 30
  • 1
    look at dom4j - http://dom4j.sourceforge.net/ Try writing some code and come back if you are having problems – Green Day Jan 14 '12 at 20:27
  • 2
    @GreenDay - While I always liked dom4j better than JDOM, unless there is a specific need, I'd strongly recommend sticking to a standard API like JAXP - instead of tightly binding the code to a particular implementation like dom4j. – ziesemer Jan 14 '12 at 20:31

2 Answers2

14

In java you use the JAXP to work with XML. You use DOM related classes to generate the xml. Below is a small example of using JAXP to create XML.

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
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.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class WriteXMLFile {

    public static void main(String argv[]) {

      try {

        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        // root elements
        Document doc = docBuilder.newDocument();
        Element rootElement = doc.createElement("company");
        doc.appendChild(rootElement);

        // staff elements
        Element staff = doc.createElement("Staff");
        rootElement.appendChild(staff);

        // set attribute to staff element
        Attr attr = doc.createAttribute("id");
        attr.setValue("1");
        staff.setAttributeNode(attr);

        // shorten way
        // staff.setAttribute("id", "1");

        // firstname elements
        Element firstname = doc.createElement("firstname");
        firstname.appendChild(doc.createTextNode("yong"));
        staff.appendChild(firstname);

        // lastname elements
        Element lastname = doc.createElement("lastname");
        lastname.appendChild(doc.createTextNode("mook kim"));
        staff.appendChild(lastname);

        // nickname elements
        Element nickname = doc.createElement("nickname");
        nickname.appendChild(doc.createTextNode("mkyong"));
        staff.appendChild(nickname);

        // salary elements
        Element salary = doc.createElement("salary");
        salary.appendChild(doc.createTextNode("100000"));
        staff.appendChild(salary);

        // write the content into xml file
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(new File("C:\\file.xml"));

        // Output to console for testing
        // StreamResult result = new StreamResult(System.out);

        transformer.transform(source, result);

        System.out.println("File saved!");

      } catch (ParserConfigurationException pce) {
        pce.printStackTrace();
      } catch (TransformerException tfe) {
        tfe.printStackTrace();
      }
    }
}
Aravind Yarram
  • 78,777
  • 46
  • 231
  • 327
  • I did this type of code but I cannot generate xml file with schema which is given in my desired xml. – saba Jan 16 '12 at 14:16
  • Thanks for your help but i didnot found any solution to generate xml file with schema. I did this type of code but I cannot generate xml file with schema which is given in my desired xml. – saba Jan 16 '12 at 14:32
  • @saba schema is also a xml so u can generate that one too – Aravind Yarram Jan 16 '12 at 18:35
  • yeap,but I didnot find any help in internet how to do that is it like to just adding node like xml.Is it possible without hard code it means schema will be generated automatically with my xml? – saba Jan 17 '12 at 05:03
  • @saba it is just like adding nodes in xml. – Aravind Yarram Jan 17 '12 at 05:09
  • like .Net is it possible schema is generated automatically with xml file in java. – saba Jan 17 '12 at 05:33
  • or I will define schema and xml file is generated automatically in java may be i think wrong i donot know actually. – saba Jan 17 '12 at 05:38
  • I used you're code and it works like a charm. The thing is, how do I get it to "newline" each element? – Moises Jimenez Dec 05 '12 at 13:27
  • Hi Aravind, which approach would be the best performance wise? To avoid using so much memory ? Isn't it better to use simply a StringBuilder? – Diego Ramos Jan 05 '21 at 22:10
0

I have an older post on my personal blog that outlines several different ways of generating XML in Java: http://blogger.ziesemer.com/2007/06/xml-generation-in-java.html

Basically, some common options to work with are JAXP, DOM, SAX (kind of a hack for generation, but it works), StAX, XSLT, or the XML binding options (JAXB) - which I did not cover in my post.

Since you already have a XML schema to work with, JAXB may work well for you. Otherwise, I'd probably go with StAX as one of the newer and efficient APIs.

ziesemer
  • 27,712
  • 8
  • 86
  • 94
  • actually I read about this API but maximum are prefer jaxb api because it is easy to generate xml schema and xml file and processing power is high is it true? – saba Jan 16 '12 at 14:14
  • I am also did not generate the schema with this xml file. – saba Jan 16 '12 at 14:22
  • I read your blog it really helpful there are so many things which i really donot know but i did not found any solution to write a xml file with schema.If you share some knowledge it is helpful for me. – saba Jan 16 '12 at 14:30
  • Still I didnot understand how o generate this xml file with schema using jaxb can u have any idea.I listen that .net can generate xml file with schema can java do that. – saba Jan 17 '12 at 14:34
  • @saba - You're looking for JAXB. Please follow the tutorial at http://docs.oracle.com/cd/E17802_01/webservices/webservices/docs/1.6/tutorial/doc/JAXBUsing.html - which specifically covers creating Java mapping classes from an XML schema. – ziesemer Jan 17 '12 at 18:06
  • Hi ziesemer, which approach would be the best performance wise? To avoid using so much memory ? Isn't it better to use simply a StringBuilder? – Diego Ramos Jan 05 '21 at 22:10
  • 1
    @DiegoRamos - Read my post as to why I'd avoid a StringBuilder. StAX will be the most memory-efficient option, at least of those listed above. Actually, with StAX plumbed directly to a file or a network stream, it can consume little-to-no memory - even less than StringBuilder. – ziesemer Jan 05 '21 at 22:23