Generation of xml file from java code

hi,
I want to manipulate data in a xml file with java code.I have read data from xml file and also changed it. But i am unable to covert it again in xml file from java code. Can you please tell me how i can do this?

Let me know which parser are you using currently for reading xml files so that i assist you. For now, you can refer to STAX Parser API under this link
http://java.sun.com/webservices/docs/1.6/tutorial/doc/SJSXP3.html

Similar Messages

  • How to modify an existing xml file from java code.

    Hi
    I have worked on creating a new xml file from java code using xmlbeans.But if i try to modify an already existing file using java code I am unable to get errorfree xmlfile.
    For example if xml file(studlist.xml) is as below:
    <?xml version="1.0" encoding="UTF-8"?>
    <StudentList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="D:\kchaitanya\xmlprac1\abc\Studlist.xsd">
         <Student>
              <Name>ram</Name>
              <Age>27</Age>
         </Student>
    <Student>
              <Name>sham</Name>
              <Age>26</Age>
         </Student>
    </StudentList>
    Now suppose i have set name to victor using student.setName,
    and set age to 20 using setAge from javacode,
    the new xml file is as follows:
    <?xml version="1.0" encoding="UTF-8"?>
    <StudentList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="D:\kchaitanya\xmlprac1\abc\Studlist.xsd">
         <Student>
              <Name>ram</Name>
              <Age>27</Age>
         </Student>
    <Student>
              <Name>sham</Name>
              <Age>26</Age>
         </Student>
    </StudentList>
    <Student>
              <Name>victor</Name>
              <Age>20</Age>
         </Student>
    As observed this is not a valid xml file.But how can i modify without any errors?

    I know it's an old post, but I found this while doing a google search for something else, and don't like to leave it un-aswered
    Just in case anyone has a similar problem... In this case the new elements have been appended outside of the root element
    What you need to do is first get the root element and then append the new children to that, there are several ways of getting the root element, which depend on what you want to do with the elements you get back here's a simple (incomplete) way.
    // gets the root element of the specified file (code not shown)
    Element rootElement= new SAXReader().read(file).getRootElement();Then just append the new elements as below (this is non-generic code and would need to be modified for your situation)
    // write a new student element
    Element student = document.createElement("Student");  // creates the new student
    rootElement.appendChild(student); // ***appends it to the root element***
    Element name = document.createElement("Name"); // creates the name element
    name.appendChild(document.createTextNode("Fred")); // adds the name text to the name element
    student.appendChild(name); // appends the name to the student
    Element age= document.createElement("Age"); // creates the age element
    age.appendChild(document.createTextNode("26")); // adds the age text to the age element
    student.appendChild(age); // appends the name to the studentThen flush ya buffers or whatever and write the file
    Edited by: Dream-Scourge on Apr 23, 2008 11:10 AM

  • How to Generate XML File from Java Code.

    I want to generate the xml file from the java code.
    Could you plz suggest any webSite address with example?

    Here is the code
    import java.io.File;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.FactoryConfigurationError;
    import javax.xml.parsers.ParserConfigurationException;
    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 class CreateXML {
         private DocumentBuilderFactory factory = null;
         private DocumentBuilder builder = null;
         private Document document = null;
         public CreateXML() {
              try {
                   factory = DocumentBuilderFactory.newInstance();
                   builder = factory.newDocumentBuilder();
                   document = builder.newDocument();
              } catch (FactoryConfigurationError e) {
                   e.printStackTrace();
              } catch (ParserConfigurationException e) {
                   e.printStackTrace();
         /** Creates the document for xml. */
         public Document createDocument(){
              try{               
                   Element root = document.createElement("Root");
                   Element child = document.createElement("child");
                   root.appendChild(child);
                   document.appendChild(root);
              }catch(RuntimeException e){
                   e.printStackTrace();
              return document;
         /** Saves the document as xml. */
         public void saveDocument(Document document){
              try{
                   TransformerFactory transFactory = TransformerFactory.newInstance();
                   Transformer transformer = transFactory.newTransformer();
                   DOMSource source = new DOMSource(document);
                   StreamResult stream = new StreamResult(new File("sample.xml"));
                   transformer.transform(source, stream);
                   System.out.println("XML Created !!");
              }catch(TransformerConfigurationException e){
                   e.printStackTrace();
              } catch (TransformerException e) {
                   e.printStackTrace();
         public static void main(String args[]){
              CreateXML createXML = new CreateXML();
              Document document = createXML.createDocument();
              createXML.saveDocument(document);
    }

  • Reference faces-config.xml file from java code.

    I would like to reference the navigation rules I have set up in my faces-config.xml file from inside my source code.
    For example:
    Navigation Rule:
    <navigation-rule>
    <from-view-id>*</from-view-id>
    <navigation-case>
    <from-outcome>pricingEngine</from-outcome>
    <to-view-id>/faces/template/t_pricing_engine.jsf</to-view-id>
    <redirect/>
    </navigation-case>
    </navigation-rule>
    I would like do some sort of lookup by 'pricingEngine' and get '/faces/template/t_pricing_engine.jsf' back.
    Any ideas?

    I would like to reference the navigation rules I have set up in my faces-config.xml file from inside my source code.
    For example:
    Navigation Rule:
    <navigation-rule>
    <from-view-id>*</from-view-id>
    <navigation-case>
    <from-outcome>pricingEngine</from-outcome>
    <to-view-id>/faces/template/t_pricing_engine.jsf</to-view-id>
    <redirect/>
    </navigation-case>
    </navigation-rule>
    I would like do some sort of lookup by 'pricingEngine' and get '/faces/template/t_pricing_engine.jsf' back.
    Any ideas?

  • How to Read and Generate XML file from java code.

    hi guys,
    how to read the xml file (Condition :we know only DTD or Shema only).
    How to Generate the new xml file ?(using Shema )
    And one more how directly Generate the xml from DB?
    Pleas with code or any URL

    Using XMLbeans you can generate Java objects from an XSD schema (perhaps DTDs aswell)
    Then you can create an instance of the Document object and ask it to write itself.
    This will create an XML document complient to the schema.
    XMLBeans generates a "type" safe DOM where you can only ever have a structure compilent to you schema.
    matfud

  • Generation of XML file from Java objects using castor

    I have the following java file(Customer.java).
    public class Customer
         private String ID;
         private FirstName firstName;
         private MiddleName middleName;
         private LastName lastName;
         private ArrayList address;
         public ArrayList getAddress() {
              return address;
         public void setAddress(ArrayList address) {
              this.address = address;
         public FirstName getFirstName() {
              return firstName;
         public void setFirstName(FirstName firstName) {
              this.firstName = firstName;
         public String getID() {
              return ID;
         public void setID(String id) {
              ID = id;
         public LastName getLastName() {
              return lastName;
         public void setLastName(LastName lastName) {
              this.lastName = lastName;
         public MiddleName getMiddleName() {
              return middleName;
         public void setMiddleName(MiddleName middleName) {
              this.middleName = middleName;
    Using castor i have created an xml file(customer.xml) which has the following format.
    <?xml version="1.0" encoding="UTF-8" ?>
    - <customer ID="fbs0001">
    <FIRSTNAME>Fred</FIRSTNAME>
    <MIDDLENAME>B</MIDDLENAME>
    <LASTNAME>Scerbo</LASTNAME>
    - <ADDRESS>
    <FIRSTLINE>No 18, Sheshadri road</FIRSTLINE>
    <SECONDLINE>Gandhinagar Bangalore</SECONDLINE>
    </ADDRESS>
    - <ADDRESS>
    <FIRSTLINE>ITPL</FIRSTLINE>
    <SECONDLINE>Whitefield Bangalore</SECONDLINE>
    </ADDRESS>
    </customer>
    I have used a mapping file to get this output.Is there a way where i can get the output xml in the following format without changing the Java object structure.If yes then please suggest how this can be done.
    <?xml version="1.0" encoding="UTF-8" ?>
    - <customer ID="fbs0001">
    <FIRSTNAME>Fred</FIRSTNAME>
    <MIDDLENAME>B</MIDDLENAME>
    <LASTNAME>Scerbo</LASTNAME>
    </customer>
    <ADDRESS>
    <FIRSTLINE>No 18, Sheshadri road</FIRSTLINE>
    <SECONDLINE>Gandhinagar Bangalore</SECONDLINE>
    </ADDRESS>
    - <ADDRESS>
    <FIRSTLINE>ITPL</FIRSTLINE>
    <SECONDLINE>Whitefield Bangalore</SECONDLINE>
    </ADDRESS>
    I mean the output xml file should have the address as a separate tag not withing the root tag customer.

    Hello,
    Castor's own discussion groups might be able to point you to the solution you're looking for (if this use case is possible using Castor).
    Oracle has its own object-to-XML mapping tool that is part of the TopLink product. It allows you to map existing objects to an existing XML Schema. This can be done visually using the TopLink Workbench, or programmatically using the TopLink APIs. TopLink OXM also supports the JAXB specification.
    Using TopLink OXM to get the desired XML result I would recommend the following. Map the Customer and Address classes to XML, but don't map the relationship between Customer and Address. Then make the calls to the marshaller something like the following:
    marshaller.marshal(aCustomer, System.out);
    for(int x=0; x<aCustomer.getAddress().size(); x++) {
         marshal(aCustomer.getAddress().get(x), System.out);
    Example - Using TopLink OXM to map an existing object model to an existing XML Schema:
    http://www.oracle.com/technology/products/ias/toplink/preview/10.1.3dp4/howto/ox/index.htm
    For more information on TopLink object-to-XML mapping:
    http://www.oracle.com/technology/products/ias/toplink/preview/10.1.3dp4/objectxml/index.html
    -Blaise

  • How to edit the existing data in the XML file from java programming.

    Hi all
    i am able to create XML file with the sample data as below from java programming.
    i need sample code on how to edit the existing data in the XML file?
    for example
    <?xml version="1.0"?>
       <mydata>
               <data1>
                         <key1>467</key1>
                        <name1>Paul</name1>
                        <id1>123</id1>
              </data1>
              <data2>
                         <key2>467</key2>
                        <name2>Paul</name2>
                        <id2>123</id2>
              </data2>
        </mydata>
    i am able to insert the data in the XML.
    now i need sample code on how to modify the data in the above XML file from the java programming for only key2,name2,id2 tags only. the remaining tags data in the XML file i want to keep same data except for key2,name2,id2 which are i want to modify from java code
    Regards
    Sunil
    [points will be always rewardable]

    hi
    u need a parser or validate the xml file for to read the xml file from java coding u need for this
    xml4j.jar u can download this file  from here
    http://www.alphaworks.ibm.com/tech/xml4j
    or we can use the SAX(simple API for XML)
    some sample applications for this
    http://www.java-tips.org/java-se-tips/javax.xml.parsers/how-to-read-xml-file-in-java.html
    http://www.developertutorials.com/tutorials/java/read-xml-file-in-java-050611/page1.html
    http://www.xml-training-guide.com/e-xml44.html
    let me know u need any other info
    bvr

  • How to call a .bat file from java code?

    How to call a .bat file from java code? and how can i pass parameters to that .bat file?
    Thanks in advance

    thanks for ur reply
    but still i am getting the same error.
    I am trying to run a .bat file of together tool, my code looks like below
    import java.lang.Runtime;
    import java.lang.Process;
    import java.io.File;
    class SysCall{
         public static void main(String args[]){
              String cmd="D://Borland//Together6.2//bin//Together.bat -script:com.togethersoft.modules.qa.QA -metrics out:D://MySamples//Metrics// -fmt:html D://Borland//Together6.2//samples//java//CashSales//CashSales.tpr";
              //String path="D://Borland//Together6.2//bin//Together.bat ";
              Runtime r= Runtime.getRuntime(); //Declare the system call
              try{
                   System.out.println("Before batch is called");
                   Process p=r.exec(cmd);
                   System.out.println(" Exit value =" + p.exitValue());
                   System.out.println("After batch is called");
              /*can produce errors which must be caught*/
              catch(Exception e) {
                   e.printStackTrace();
                   System.out.println (e.toString());
    I am getting the below exception
    Before batch is called
    java.lang.IllegalThreadStateException: process has not exited
    at java.lang.Win32Process.exitValue(Native Method)
    at SysCall.main(SysCall.java:17)
    java.lang.IllegalThreadStateException: process has not exited

  • How I can create a XML file from java Aplication

    How I can create a XML file from java Aplication
    whith have a the following structure
    <users>
    <user>
    <login>anyName</login>     
    <password>xxxx</password>
    </user>
    </users>
    the password label must be encripted
    accept any suggestion

    Let us assume you have all the data from the jsp form in an java bean object..
    Now you want a xml file. This can be acheived in 2 ways
    1. Write it into a file using java.io classes. Say you have a class with name
    write("<name>"+obj.getName+</name>);
    bingo you have a flat file with the xml
    2. Use data binding to do the trick
    will recommend JiBx and Castor for the 2nd option
    Regards,
    Rajagopal

  • Creating XML file from Java Bean

    Hi
    Are there any standard methods in Java 1.5 to create XML file from java bean,
    i can use JAXB or castor to do so,
    But i would like to know if there is any thing in java core classes,
    I have seen XMLEncoder, but this is not what i want.
    Any ideas
    Ashish

    Marshall JavaBean to an XML document with JAXB or XMLBeans.

  • Starting exetutable java file from java code

    Hi I was wondering how I can start a executable java file from java code?
    thanks

    Hi Mkaveli,
    Yes, it's possible. If you have a JAR executable, you've just to call the main method of its starter class. For a simple executable class, just call its main method.
    This way :
    SomeStarter.main(null); // if there's no argumentSmall precision : the executable JAR or class must be specified in the classpath of your application.

  • How to read XML files from java

    i need a sugession that how to read a xml file using java code
    and i need to parse using some parsers and display attributes and entity seperately
    as a string.......

    import org.dom4j.Document;
    import org.dom4j.DocumentException;
    import org.dom4j.io.SAXReader;
    import java.io.File;
    import java.text.AttributedCharacterIterator.Attribute;
    import java.util.Iterator;
    import java.util.StringTokenizer;
    public class XmlParser
    private String Result="";
    private String Final="";
    private String Delim="";
    public void bar1(Document document) throws DocumentException
    org.dom4j.Element root = document.getRootElement();
    // System.out.println(root.getName());
    bar2(root);
    System.out.println(this.Result);
    process();
    public void bar2(org.dom4j.Element e)
    for(Iterator i = e.elementIterator();i.hasNext();)
    org.dom4j.Element Element = (org.dom4j.Element) i.next();
    Result += Element.getName()+"\t"+Element.getText()+"\n";
    bar2(Element);
    public void process()
    StringTokenizer Tokenizer = new StringTokenizer(this.Result,"\n");
    String element;
    while(Tokenizer.hasMoreTokens())
    element = Tokenizer.nextToken();
    StringTokenizer Tokenizer2 = new StringTokenizer(element,"\t");
    // Do what ever String Process here Example
    this.Final += element.getName();
    this.Final += this.Delim;
    System.out.println(this.Final);
    public static void main(String s[])throws Exception
    Document document = null;
    SAXReader reader = new SAXReader();
    File f1= new File("D:/Rajesh/EDI to XML/EDI.xml");
    document = reader.read(f1);
    Demo obj = new Demo();
    obj.bar1(document);
    i think this will hep full.......

  • How to pass arguments to a batch file from java code

    Hi
    I have a batch file (marcxml.bat) which has the following excerpt :
    @echo off
    if x==%1x goto howto
    java -cp C:\Downloads\Marcxml\marc4j.jar; C:\Downloads\Marcxml\marcxml.jar; %1 %2 %3
    goto end
    I'm calling this batch file from a java code with the following line of code:
    Process p = Runtime.getRuntime().exec("cmd /c start C:/Downloads/Marcxml/marcxml.bat");
    so ,that invokes the batch file.Till that point its ok.
    since the batch file accpets arguments(%1 %2 %3) how do i pass those arguments to the batch file from my code ...???
    %1 is a classname : for ex: gov.loc.marcxml.MARC21slim2MARC
    %2 is the name of the input file for ex : C:/Downloads/Marcxml/source.xml
    %3 is the name of the output file for ex: C:/Downloads/Marcxml/target.mrc
    could someone help me...
    if i include these parameters too along with the above line of code i.e
    Process p = Runtime.getRuntime().exec("cmd /c start C:/Downloads/Marcxml/marcxml.bat gov.loc.marcxml.MARC21slim2MARC C:\\Downloads\\Marcxml\\source.xml C:\\Downloads\\Marcxml\\target.mrc") ;
    I get the following error :
    Exception in thread main java.lang.Noclassdef foundError: c:Downloads\marcxml\source/xml
    could some one tell me if i'm doing the right way in passing the arguments to the batch file if not what is the right way??
    Message was edited by:
    justunme1

    1 - create a java class (Executer.java) for example:
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    public class Executer {
         public static void main(String[] args) {
              try {
                   for (int i = 0; i < args.length; i++) {
                        System.out.println(args);
                   Class<?> c = Class.forName(args[0]);
                   Class[] argTypes = new Class[] { String[].class };
                   Method main = c.getDeclaredMethod("main", argTypes);
                   // String[] mainArgs = Arrays.copyOfRange(args, 1, args.length); //JDK 6
                   //jdk <6
                   String[] mainArgs = new String[args.length - 1];
                   for (int i = 0; i < mainArgs.length; i++) {
                        mainArgs[i] = args[i + 1];
                   main.invoke(null, (Object) mainArgs);
                   // production code should handle these exceptions more gracefully
              } catch (ClassNotFoundException x) {
                   x.printStackTrace();
              } catch (NoSuchMethodException x) {
                   x.printStackTrace();
              } catch (IllegalAccessException x) {
                   x.printStackTrace();
              } catch (InvocationTargetException x) {
                   x.printStackTrace();
              } catch (Exception e) {
                   e.printStackTrace();
    2 - create a .bat file:
    @echo off
    java -cp C:\Downloads\Marcxml\marc4j.jar; C:\Downloads\Marcxml\marcxml.jar; Executer %TARGET_CLASS% %IN_FILE% %OUT_FILE%3 - use set command to pass variable:
    Open MS-DOS, and type the following:
    set TARGET_CLASS=MyTargetClass
    set IN_FILE=in.txt
    set OUT_FILE=out.txt
    Then run your .bat file (in the same ms dos window)
    Hope that Helps

  • Merge two XML files From java

    hi,
    i'm in need to merge two XML files from my java code please help me as soon......

    Rajesh42 wrote:
    hi,
    i'm in need to merge two XML files from my java code please help me as soon......Hello Rajesh42,
    While it is wonderful that you have discovered the magically code tags, please consider if it is the right time to use them. Code tags should only go round code. Note used to make your posts "stand out", or used to quote other people. Just code.
    As to your question, what have you tried, what are you stuck on?
    Mike

  • Creating an xml file from abap code

    Hello All,
    Please let me know which FM do I need to execute in order to create an XML file from my ABAP code ?
    Thanks in advance,
    Paul.

    This has been discussed before
    XML files from ABAP programs

Maybe you are looking for

  • Differentiating/Sharing Music Between Mac Accounts

    Hey, all! I am prepping to get a new Mac, and I have a deboccale that I'm trying to figure out. My fiance and I will have separate accounts on the computer for iCloud and other purposes. However, I have an extensive library of music that I would like

  • Is there a way to find out what apps belong to a certain account

    I am having problems updating my apps. I love that little Update All button in iTunes but it is rather useless when there is at least one app mixed in that came from another account. When iTunes hits this one app it stops checking all the rest for up

  • Problems with 3.1.2 download, & iTunes dates...

    So I purchased the 3.1.2 update and it did not download. It went to download 3.1.1. strange... It does not download citing a network connection. On my end I'm ok because you are reading my post so could it be from apple's side? Also, purchased it tod

  • Reader Toolbar not Working in Internet Explorer

    I can open a PDF file in IE or Firefox; however, none of the options on the toolbar work. For example, if I click on the disk icon to save a PDF, my cursor turns to a circle with a slash throught it. I tried removing Reader and reinstalling without l

  • Image displays in some jsp files but not others

    OK, I have a jsf jsp pages js tag for my application that occurs in several jsp pages: <tr>    <td>       <jsp:include page="/includes/footer.jsp"/>    </td> </tr>     footer.jsp has an image tag like this: <td align="left"><img src="images/logo.jpg"