Modify existing XML file

Ok I really need some help...What is the JAVA code that i need to add something to an existing XML file. Basically, I want to add a new tag at the end of another one. So I need to search the XML file for the end of one tag, and then add a new tag after that one. Please help.

Sounds like you think it's simple. There is a set of XML tutorials here:
http://java.sun.com/webservices/docs/1.0/tutorial/index.html
You probably need the one titled "Document Object Model" but it may help to read some of the others too.

Similar Messages

  • Changing an existing XML-File

    Hello everybody,
    is there any way to change an existing xml file (adding an xml element, for example), without copy the hole file?
    I've found kxml2 which can parse the xml files or build new xml files, but it doesn't support changing...
    Thank you
    Micha

    Pradeep thank you for your response. it was helpful. However, I also found the responses to both my questions.
    i. The null pointer exception was due to using a complex query I was using in the LOV query. I tried a simple query and that worked fine.
    ii. For modifying the user defined attributes one can consult the following forum post:
    OIM 11g - Change UDF Field Type form String to LOV
    Thanks

  • How do i update an existing XML File?

    Hello, I have the following xml file gps.xml:<?xml version="1.0"?>
    <!DOCTYPE gps SYSTEM "gps.dtd">
    <gps>
       <latitude>43.00000</latitude>
       <longitude>-83.00000</longitude>
    </gps> I already have methods written to get the values. But how can I change these values and update the file to reflect these changes?
    thanks for your help!

    Hi, I already have this following code. I would just like to add a method to it to update the existing XML file with different lat/lon coordinates. Could you please help me out with it? thanks
    import java.io.*;
    import java.io.PrintWriter;
    import java.net.MalformedURLException;
    import java.net.URL;
    import javax.xml.parsers.*;
    import org.w3c.dom.*;
    import org.xml.sax.*;
    public class Gps implements java.io.Serializable {
        private double latitude_;
        private double longitude_;
        public Gps(Document doc) {
            setup(doc.getDocumentElement());
        public Gps(String uri) throws IOException, SAXException, ParserConfigurationException {
            setup(uri);
        public void setup(Document doc) {
            setup(doc.getDocumentElement());
        public void makeElement(Node parent) {
            Document doc;
            if (parent instanceof Document) {
                doc = (Document)parent;
            } else {
                doc = parent.getOwnerDocument();
            Element element = doc.createElement("gps");
            int size;
            URelaxer.setElementPropertyByDouble(element, "latitude", this.latitude_);
            URelaxer.setElementPropertyByDouble(element, "longitude", this.longitude_);
            parent.appendChild(element);
         public Document makeDocument() throws ParserConfigurationException {
            Document doc = UJAXP.makeDocument();
            makeElement(doc);
            return (doc);
        public final double getLatitude() {
            return (latitude_);
        public final void setLatitude(double latitude) {
            this.latitude_ = latitude;
        public final double getLongitude() {
            return (longitude_);
        public final void setLongitude(double longitude) {
            this.longitude_ = longitude;
       public final void updateXmlFile(double latitude, double longitude) {
         // something???
        public final void updateXmlFile(double latitude, double longitude) {
            this.latitude_ = latitude;
            this.longitude_ = longitude;
        public String makeTextDocument() {
            StringBuffer buffer = new StringBuffer();
            makeTextElement(buffer);
            return (new String(buffer));
        public void makeTextElement(StringBuffer buffer) {
            int size;
            buffer.append("<gps");
            buffer.append(">");
            buffer.append("<latitude>");
            buffer.append(Double.toString(getLatitude()));
            buffer.append("</latitude>");
            buffer.append("<longitude>");
            buffer.append(Double.toString(getLongitude()));
            buffer.append("</longitude>");
            buffer.append("</gps>");
        public String toString() {
            try {
                return (makeTextDocument());
            } catch (Exception e) {
                return (super.toString());
    }

  • How to update Elements value inside existing xml file

    Hi Gurus,
    Am somehow new to java and working on xml with java, i have a scenario where i want to update the elements of my existing xml file, i know its possible as i have posted one code on this forum which updates the values of the arrtibutes of existing xml file. Ref :
    http://forum.java.sun.com/thread.jsp?forum=34&thread=186091&start=15&range=15&hilite=false&q=
    But am not able to use the same code to update the vlaues of the attribute.
    if i have this xml file :
    <?xml version="1.0"?>
    <RootElement>
    <Transaction>
    <Task9>
    <TaskID>Task9</TaskID>
    <Description>My Test Case</Description>
    <Time>12/12/2004</Time>
    </Task9>
    </Transaction>
    <Transaction>
    <Task2>
    <TaskID>Task2</TaskID>
    <Description>Testing my xml</Description>
    <Time>12/12/2004</Time>
    </Task2>
    </Transaction>
    </RootElemen>
    Now i want to update teh </Description> and </Time> field using the code that i have given above in the link.
    If any one can help me ill really appreciate.

    The value of an element is stored in a child node of that element. For example, let's say that "e" references the node <Description> then:
    e.getFirstChild().getNodeValue() => "My Test Case"

  • 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

  • I am unabele to create nodes to existing xml file

    I want to append and update the nodes and attributes to existing xml file.
    presently am using dom api, am i do that with dom or sax,if so how can i plz ...

    http://java.sun.com/xml/tutorial_intro.html

  • How I can append new node in existing  XML file

    I've just begun learning DOM XML , so I'm currently at a very beginner level.
    I have an existing XML file that I would like to add an additional node to before saving it to another variable.
    how I can append new node in this file.
    now this code is overwrite new data over old data
    The code looks like this:
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import javax.xml.transform.Result;
    import javax.xml.transform.Source;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.TransformerFactoryConfigurationError;
    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 VerbXMLWriter
        static String EVerb3;
        static String englishTranslate3;
        public void VerbXMLWriter(String EVerb, String englishTranslate )
             EVerb3 = EVerb;
             englishTranslate3=englishTranslate;
        File xmlFile = new File("VerbDB.xml");
        DocumentBuilderFactory factory =  DocumentBuilderFactory.newInstance();
        try
         DocumentBuilder builder = factory.newDocumentBuilder();
         Document document = builder.newDocument();
        Element root = document.createElement("Verb");
         document.appendChild(root);
         Element verb = document.createElement(EVerb3);
         verb.setAttribute("EnglishTranslate",englishTranslate3);
         root.appendChild(verb);
         Source xmlSource = new DOMSource( document );
         Result result = new StreamResult( new FileOutputStream(xmlFile) );
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer =
        transformerFactory.newTransformer();
        transformer.setOutputProperty( "indent", "yes" );
         transformer.transform( xmlSource, result );
      catch(TransformerFactoryConfigurationError factoryError )
        factoryError.printStackTrace();
       catch (ParserConfigurationException pc)
           pc.printStackTrace();
       catch (IOException io)
          io.printStackTrace();
       catch(Exception excep )
           excep.printStackTrace();
    <?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <Verb>
    <Play EnglishTranslate="playing" />
    </Verb>Edited by: itb402 on Mar 9, 2008 6:05 AM

    in your code you are already appending new nodes to the root node. so what exactly is your problem? The following steps are usually taken for appending a new node:
    1. Read the XML document
    2. Build a DOM tree
    3. Navigate to the node under which you want to insert the new node
    4. Create a new node.
    5. Insert the new node to the node selected in point #3.
    ~Debopam

  • Updating an existing  xml file in java

    Hi,
    i need to update an existing xml file with new nodes. But i don.t know how to do that. i can read and write a new xml file . But updaton seems too difficult for me.
    my xml structure is like this
    <main_node>
    <node1>
    <name> name1</name1>
    <id>ID</id>
    </node1>
    <node2>
    <name2> name2</name2.
    <id>ID</id>
    </node2.
    </main_node>
    i want to insert node3 in this structure.
    please help, it,s urgent;
    Thanks in Advance

    here is the code if ur using dom..
    Node node4 = doc.createTextNode(name3);
    Element element4=doc.createElement("name3");
    element4.append(node4);
    c one thing that u should take care here is that u have created and is reflected on ly in ur document object and not in xml..for that u have to write some more code like this
    // This method writes a DOM document to a file
    public static void writeXmlFile(Document doc, String filename) {
    try {
    // Prepare the DOM document for writing
    Source source = new DOMSource(doc);
    // Prepare the output file
    File file = new File(filename);
    Result result = new StreamResult(file);
    // Write the DOM document to the file
    Transformer xformer = TransformerFactory.newInstance().newTransformer();
    xformer.transform(source, result);
    } catch (TransformerConfigurationException e) {
    } catch (TransformerException e) {
    look this code..that will help u
    regards
    [email protected]

  • How can I affix Data to a existing XML file?

    Hallo.
    I have to write Data to an XML file. This I have to in a stacked Sequence within a while loop. How can I write my Data to my existing XML file without overwriting my existing Data from the loop before?
    Thanks

    I made the erroneous assumption that you were using your own XML creation code.  The LabVIEW write to XML file VI overwrites the file every time.  You can get around this behavior in  a couple of ways.
    Create your own write to XML VIs using the LabVIEW one as your base.  The LabVIEW one write a header, writes your data, then writes the end tag.  Split this up so that you open the file and write the header before your loop.  During the loop, write your data.  Write the end tag and close the file when you exit the loop.  Don't overwrite the LabVIEW vi.lib function, or you will probably regret it.  Copy it to a different location before you start your modifications.
    Use the LabVIEW write to XML file for the first write of the loop.  This will give you a file with a header and your first set of data.  Still in the first loop iteration, reopen the file and position the file pointer on the start of the end tag (</LVData>).  In subsequent loop operations, flatten your data to XML and write to the file directly using the file write primitive.  When you exit your loop, write an end-of-line character and the end tag "</LVData>" and close the file.
    If you need more detailed help on either of the above methods, let me know.
    Out of curiosity, why are you saving your data as XML?  There may be a better way to do it, depending on your application.
    This account is no longer active. Contact ShadesOfGray for current posts and information.

  • 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 create and modify an XML file from an Oracle Form

    I would like to build an Oracle Form to maintain a small XML file in the file system (i.e. Not in Oracle database but in the operating system).
    I would like the Form to display existing values from the XML file and the user can update and save content back to the XML file.
    Can any one tell me how this can be done? Thanks.

    Does Forms 9i provide any XML Parser Functions?
    Can I insert the XML file into a table column by inserting XML using the XSU Front End rather than using TEXT_IO to maintain the XML file directly?
    Can I use XSU PL/SQL API in Forms to retrieve and modify XML values?
    Any help is appreciated.

  • Modifying existing jar file, how?

    Hi there,
    I have a problem trying to modify an existing jar file. When I want to create a jar file, I use something like:
    REM build the application on windows, assuming the java/bin
    REM directory is in the path environment variable
    REM application is just the directory I am using
    SET cp = c:\application\TestApp
    javac -classpath %cp% TestApp.java
    REM ****************************************
    REM do packaging and adding manifest
    REM ****************************************
    jar cvfm App.jar manifest.mf TestApp*.class
    REM ****************************************
    REM run the jar file
    REM ****************************************
    javaw -jar App.jar
    But now, I have an existing jar file (swingall.jar) and I want to modify a class within that file. So, I modified the .java file, and compiled it to get my new class file.
    And the question is, how do I modify the existing file, so that I keep everything the same, except the modified class?
    Thanks
    Fernando

    I have just found out that I can't use "u". It seemsthat's only
    possible with older versions of jar.Huh? I'm using the 1.4.2-b28 jdk, it's still there,
    and I don't see how it could ever possibly be
    removed.
    Type:
    jar
    with no arguments to see all the options to jar.I already did, to double check it, and this is what I got:
    C:\Documents and Settings\Fernando Sanz>jar
    Usage: jar {ctx}[vfm0M] [jar-file] [manifest-file] files ...
    Options:
    -c create new archive
    -t list table of contents for archive
    -x extract named (or all) files from archive
    -v generate verbose output on standard error
    -f specify archive file name
    -m include manifest information from specified manifest file
    -0 store only; use no ZIP compression
    -M Do not create a manifest file for the entries
    If any file is a directory then it is processed recursively.
    The manifest file name and the archive file name needs to be specified
    in the same order the 'm' and 'f' flags are specified.
    Example: to archive two class files into an archive called classes.jar:
    jar cvf classes.jar Foo.class Bar.class
    Note: use the '0' option to create a jar file that can be put in your CLASSPATH
    Thanks for trying with jdk 1.4, I don't have it installed in my computer right now, so I'll try tomorrow with another computer at Uni.
    Thanks!

  • Read and write existing xml file trouble !

    Hi everyone ! 
    i'm trying to save hight score of user in my game by using a xml file , in my xml file has element <best_score>0<best_score/>
    and my code to do it is : 
     XElement best=XElement.Load("Assets/best.xml");
                IEnumerable<XElement> loc = best.Elements("best_score");
                foreach (XElement elem in loc)
                    int check=Convert.ToInt32(elem.Value.ToString());
                    int score_user = Convert.ToInt32(scores.ToString());
                    if (score_user >= check)
                       hight_score.Text = score.ToString();
                         elem.Value = scores.ToString();
                         // what code to save this  xml file  after modify ?????
                    else
                        list_box.Text = check.ToString();
    i down know what method can help me save my xml file after update hight score of user in this case .  
    Anyone has an idea to solve it for me ? please , thanks you ! 
    sorry about my english ! 

    Hi,
    It is not recommended to update a file withing the project, so you need to store it in the IsolatedStorage.
    Here is a sample to read and write file in IsolatedStorage,
    XDocument xDoc;
    var file = Util.ReadFile("XMLFile.xml");
    if (file != null)
    xDoc = XDocument.Parse(file);
    var bestScore = xDoc.Element("best_score").Value;
    //do calculation
    xDoc.Element("best_score").Value = "200";
    Util.SaveFile("XMLFile.xml", xDoc.ToString());
    For the above code to work, you need to have a file named "XMLFile.xml" in your IsolatedStorage, with data as  "<best_scrore>200</best_scrore>"
    To read and write file:
    public static class Util
    public static void SaveFile(string filename, string data)
    try
    using (var store = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication())
    using (var stream = new IsolatedStorageFileStream(filename, FileMode.Create, FileAccess.ReadWrite, store))
    StreamWriter writer = new StreamWriter(stream);
    writer.Write(data);
    writer.Close();
    catch (Exception)
    Debug.WriteLine("Couldn't save the file.");
    public static string ReadFile(string filename)
    try
    String data;
    if (!IsolatedStorageFile.GetUserStoreForApplication().FileExists(filename)) return null;
    using (var store = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication())
    using (var stream = new IsolatedStorageFileStream(filename, FileMode.Open, FileAccess.ReadWrite, store))
    StreamReader stmReader = new StreamReader(stream);
    data = stmReader.ReadToEnd();
    stmReader.Close();
    return data;
    catch (Exception)
    return null;
    Pradeep AJ

  • BC4J can't find existing xml file

    hi, following a debug output with a "file not found" error.
    the problem is, the file exist.
    is it possible the container look in root directory?
    [76] No xml file: /com/eautop/bc/master/master.xml, metaobj = com.eautop.bc.master.masterot directory
    following the line around the error. i assume the outofmemory exception will be a follow up to the previous one.
    any hints?
    regards
    wolfgang gillich
    [65] Diagnostic Properties: Timing:false Functions:false Linecount:true Threshold:6
    [66] JavaVMVersion: 1.3.0-1
    [67] JavaVMVendor: Compaq Computer Corp.
    [68] JavaVMName: Classic VM
    [69] OperatingSystemName: OSF1
    [70] OperatingSystemVersion: V4.0
    [71] OperatingSystemUsername: oracle
    [72] Connected to Oracle JBO Server - Version: 3.2.9.76.3
    [73] {{+++ id=10000 type: 'BC4J_CREATE_ROOTAM' Create Root Application Module 'com.eautop.bc.master.MasterAppModule'
    [74] {{+++ id=10001 type: 'METAOBJECT_LOAD' Loading meta-object: com.eautop.bc.master.MasterAppModule
    [75] {{+++ id=10002 type: 'METAOBJECT_LOAD' Loading meta-object: com.eautop.bc.master.master
    [76] No xml file: /com/eautop/bc/master/master.xml, metaobj = com.eautop.bc.master.master
    [77] CSMessageBundle (language base) being initialized
    [78] }}+++ End Event10003 null
    [79] Cannot Load parent Package : com.eautop.bc.master.master
    [80] Business Object Browsing may be unavailable
    [81] No xml file: /com/eautop/bc/master/MasterAppModule.xml, metaobj = com.eautop.bc.master.MasterAppModule
    [82] }}+++ End Event10002 null
    java

    Hello,
    I'm trying to learn how to use an xml file to store user settings for an add in I'm creating. Up to this point, I've just used simple text files in the past that were structured a specific way. I thought I would try and learn to use XML for this after doing
    some research online and came across this tutorial:
    http://www.codeproject.com/Articles/8554/Application-Settings-the-NET-way-INI-Registry-or-X
    I add the DataSet to my project, but when I get to the step where I'm supposed to add an element to the blank DataSet, I can't find the XML Schema toolbox items. I tried to manually add the toolbox items but couldn't find them. Does anyone know where they
    are located so I can add them to my toolbox? Or perhaps another similar tutorial I could follow for creating an XML settings file that I can save to and read from easily for my add in. Since it is a dll, I can't use My.Settings, had already looked into that.
    I appreciate any help offered, Thank you.
    Is there a reason that you don't want to use Application Settings?
    By the way - it's saved in XML format, not that that's really important.
    Still lost in code, just at a little higher level.

  • Modify existing excel file (POI API)

    Hi All,
    Can anybody give me a reference to an example to update/modify an exsiting excel file in java.
    For creation of excel file I am using POI API. But not getting how to update an existing excel file
    using POI API.
    I'll be thankful for your help.
    Regards
    Naz

    Tabbasum wrote:
    Hi All,
    Can anybody give me a reference to an example to update/modify an exsiting excel file in java.
    For creation of excel file I am using POI API. But not getting how to update an existing excel file
    using POI API.
    I'll be thankful for your help.
    Regards
    NazYou do know that the poi.apache.org site has some nice examples, don't you?
    http://poi.apache.org/spreadsheet/examples.html
    Many other examples exist on the Internet; Google is your friend.
    Hope that helps, Naz.
    Regards,
    Jay-Z

Maybe you are looking for

  • How to Print when printer is NOT AirPrint capable

    I have an iPad 2 and would like to print.  My computer is a Canon PIXMA MX870.  It is wireless but not AirPrint capable, as far as I can tell. I have downloaded the Printer Pro app and tried to find my printer.  Both my desktop computer (iMac) and pr

  • I have a Mac Mini late 2012 version and i am trying to reset to factory setting.

    Hello, I had a bought a Mac Mini late 2012 version a couple months ago, and after i tried to install "pro tool" on my Mac, and FAILED. my Garage band wouldn't open anymore. it only tells me "garage band quit unexpectedly" when i open it. I tried unin

  • Windows 8.1 pro WIFI issues

    After updating to windows 8.1 pro from windows 8.1 preview, wifi is showing "No internet access". no issue with router as it is working on other devices. Tried disable-enable. tried re install. tried updating driver. nothing seems to work. any help w

  • K9VGM-V vs skype video calling

    When I launched viceo calling in skype http://kepfeltoltes.hu/061018/k9vgmvsypevideo_www.kepfeltoltes.hu_.jpg bsod in matrix style 

  • Huge file in camera roll I can't get of phone

    I have a video file on my camera roll that I can't get of my phone. I prosume it's about a gig as it was left on in my pocket until my phone ran out of power, but I want to keep it. Image capture shows the file but it was greyed out and just froze fo