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

Similar Messages

  • 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

  • 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

  • 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

  • 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);
    }

  • Updating an existing xml file using java code

    hi friends,
    I have simple problem, I have an existing xml file and I want to update some of the values in the file.
    can any one send me the java code for that.
    bye.
    -harish

    org.w3c.dom.Document d = parseXmlFile("D:/www/Detailcache/detail.xml", false);
    public static Document parseXmlFile(String filename, boolean validating) {
    try {
    // Create a builder factory
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(validating);
    // Create the builder and parse the file
    Document doc = factory.newDocumentBuilder().parse(new File(filename));
    return doc;
    } catch (Exception e) {
    System.out.println("ERROR-->");e.printStackTrace();
    return null;
    look at .. for more related examples
    http://javaalmanac.com/egs/javax.xml.parsers/BasicDom.html?l=rel

  • 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?

  • XML data storage - How to handle symbol ' inside xml data from java code

    Hi
    I'm trying to store XML data in Oracle XML DB 10gR2 both through SQL and JAVA .
    I have a simple test table called xmltable with a primary key and a XMLType column
    My sql is:
    insert into xmltable values ('020', sys.XMLType.CreateXML(
    '<?xml version="1.0"?>
    <Mpeg7 xmlns="urn:mpeg:mpeg7:schema:2001">
    <DescriptionMetadata id="2005">
    <LastUpdate>2006-10-19T12:48:22.null+01:00</LastUpdate>
    <Creator/>
    <CreationTime>2006-10-19T12:48:22.null+01:00</CreationTime>
    <Instrument>
    <Tool>
    <Name>LAS MPEG-7 Services v1.0</Name>
    </Tool>
    </Instrument>
    </DescriptionMetadata>
    <Description xsi:type="urn:ContentEntityType" xmlns:urn="urn:mpeg:mpeg7:schema:2001" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <MultimediaContent xsi:type="urn:ImageType">
    <Image id="2005">
    <MediaInformation>
    <MediaProfile>
    <MediaFormat>
    <Content/>
    <Medium href="urn:mpeg:MPEG7MediumCS:2.1.1"/>
    <FileFormat href="urn:mpeg:IPTCMimeTypeCS:image/jpeg"/>
    <FileSize>2782043</FileSize>
    <VisualCoding>
    <Format colorDomain="color" href="urn:mpeg:MPEG7VisualCodingFormatCS:1"/>
    <Frame height="11604" width="8676"/>
    </VisualCoding>
    </MediaFormat>
    </MediaProfile>
    </MediaInformation>
    <MediaLocator>
    <MediaUri>oracle:bosch.informatik.rwth-aachen.de:1521/SMILEY/AMSDB.MEDIA_IMAGE/IMAGE[IMG_ID=2005]</MediaUri>
    </MediaLocator>
    <TextAnnotation>
    <FreeTextAnnotation>B?miy?n and Shikari areas</FreeTextAnnotation>
    </TextAnnotation>
    <Semantic>
    <SemanticBaseRef href="oracle:bosch.informatik.rwth-aachen.de:1521/SMILEY/AMSDB.OBJECT_XML/MPEG7_SB#/mpeg7:Mpeg7/mpeg7:DescriptionMetadata[@id='65']"/>
    <SemanticBaseRef href="oracle:bosch.informatik.rwth-aachen.de:1521/SMILEY/AMSDB.OBJECT_XML/MPEG7_SB#/mpeg7:Mpeg7/mpeg7:DescriptionMetadata[@id='148']"/>
    </Semantic>
    </Image>
    </MultimediaContent>
    </Description>
    </Mpeg7>
    Unfortunately I'm facing problem with the symbol ' at the tags:
    <SemanticBaseRef href="oracle:bosch.informatik.rwth-aachen.de:1521/SMILEY/AMSDB.OBJECT_XML/MPEG7_SB#/mpeg7:Mpeg7/mpeg7:DescriptionMetadata[@id='65']"/>
    <SemanticBaseRef href="oracle:bosch.informatik.rwth-aachen.de:1521/SMILEY/AMSDB.OBJECT_XML/MPEG7_SB#/mpeg7:Mpeg7/mpeg7:DescriptionMetadata[@id='148']"/>
    If I tried with double ' (not '' ) it works with SQL through SQLPLUS but not with java. Indeed I have to store the data through my application
    In java I get java.sql.SQLException: ORA-19102
    Many thanks in advance,
    Evanela

    Thanks for your answer. I downloaded the JDBC AddressBook application and I found it very usefull. I was able to populate a datalist from a datasource and show it in my application. My problem still remains in the sense that I am unable to show the KPI data in a "custom node" meaning I woul like not only to extract directly the database record to a datalist object but also put the information of a single record in a textbok and a gauge and keep control of paging. I think this is done with the parser in the other examples but I can not figure out how to do it with MySQL and the new Desktop screen designer. Should I use a clip object? or is that managed already by the desktop screen designer? or where can I find an example with the functionality I need?.

  • 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 I could generate an XML file from a report in version 4.0B

    Good morning,
    How could I generate an XML file from a report? Please note that I am using version 4.0B
    I don't have access to
    Billy Vital

    Hi,
            In the Class CL_XML_DOCUMENT,
                 we have a method  EXPORT_TO_FILE to download an XML file.

  • 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 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

  • 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.

  • How can i call forpro prg file from java

    Hai friends,
    I have a doubt,clear it.
    how can i call forpro prg file from java file
    by,
    N.Vijay

    Thanks to your reply,
    I have some print statements in my foxpro program file.
    Then i like to invoke that foxpro file from my java file
    This want i want..,
    by,
    N.Vijay

  • 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.

Maybe you are looking for

  • How do I share files uploaded into the Creative Cloud with other creative cloud members?

    How do I share files uploaded into the Creative Cloud with other creative cloud members?

  • Disk Error Midway through a Backup

    I am about to upgrade to Windows Vista, before doing so I wanted to Backup my itunes Library. Everything was going fine with the backup until I hit disk 5 (out of 6). Prior to it being finished I encountered a disk error, itunes gave me the option of

  • Animating a sequence of still images

    I wonder if you happen to know a quick way to do this in Final Cut Pro: I've got 750 (or some other fairly large number of) still images I want to animate. 1) I want to drop all 750 into a sequence, ordered by name (so the 1st image is called (someth

  • I can't open Photoshop Elements 11 after a redownload.

    I am trying to redownload Photoshop Elements 11 on my new PC. There are 2 files to download.  I can't download the second file, nor can I open it. I get an error message that says I am missing the "archive file part."  What do I do?

  • Openining multiple web pages

    Hi When i run my report thru WAD development server, some 100's of web pages are getting openend. I had to close the session and restart again. BUT When i run the report thru WAD in QA and PRD they run fine. IS there any setting we need to do in DEV