How to modify a xml file?

I use JAXP 1.1 to read a xml file as a DOM tree. I can make change to the DOM tree in the memory, such as add an element or change the node value, but how can I apply these changes to the source xml file, i.e., write the changes back to the disk?

you can write an xml file using DOMWriter.
copy and compile this class
and then use it:
PrintWriter printWriter = //create a printWriter form your xml file
DOMWriter writer = new DOMWriter(printWriter);
writer.print(myXml.toString());
package Zeus.core.XML;
import java.io.*;
import org.w3c.dom.*;
* @author Rodrigo Gonzalez Asensio
* @email [email protected]
public class DOMWriter {
   protected PrintWriter out;
   protected boolean canonical;
   protected String encoding;
public DOMWriter(OutputStreamWriter out) throws UnsupportedEncodingException {
     this(out, false);
public DOMWriter(OutputStreamWriter out, boolean canonical)
     throws UnsupportedEncodingException {
     encoding = out.getEncoding();
     if (encoding == null) {
          throw new UnsupportedEncodingException(out.getEncoding());
     this.out = new PrintWriter(out);
     this.canonical = canonical;
/** Normalizes the given string. */
protected String normalize(String s) {
     StringBuffer str = new StringBuffer();
     int len = (s != null) ? s.length() : 0;
     for (int i = 0; i < len; i++) {
          char ch = s.charAt(i);
          switch (ch) {
               case '<' :
                         str.append("<");
                         break;
               case '>' :
                         str.append(">");
                         break;
               case '&' :
                         str.append("&");
                         break;
               case '"' :
                         str.append(""");
                         break;
               case '\r' :
               case '\n' :
                         if (canonical) {
                              str.append("&#");
                              str.append(Integer.toString(ch));
                              str.append(';');
                              break;
                         // else, default append char
               default :
                         str.append(ch);
     return (str.toString());
public void print(Node node) {
     // is there anything to do?
     if (node == null) {
          return;
     int type = node.getNodeType();
     switch (type) {
          // print document
          case Node.DOCUMENT_NODE :
                    if (!canonical) {
                         out.println("<?xml version=\"1.0\" encoding=\"" + encoding + "\"?>");
                    print(((Document) node).getDocumentElement());
                    out.flush();
                    break;
               // print element with attributes
          case Node.ELEMENT_NODE :
                    out.print('<');
                    out.print(node.getNodeName());
                    Attr attrs[] = sortAttributes(node.getAttributes());
                    for (int i = 0; i < attrs.length; i++) {
                         Attr attr = attrs;
                         out.print(' ');
                         out.print(attr.getNodeName());
                         out.print("=\"");
                         out.print(normalize(attr.getNodeValue()));
                         out.print('"');
                    out.print('>');
                    NodeList children = node.getChildNodes();
                    if (children != null) {
                         int len = children.getLength();
                         for (int i = 0; i < len; i++) {
                              print(children.item(i));
                    break;
               // handle entity reference nodes
          case Node.ENTITY_REFERENCE_NODE :
                    if (canonical) {
                         NodeList children = node.getChildNodes();
                         if (children != null) {
                              int len = children.getLength();
                              for (int i = 0; i < len; i++) {
                                   print(children.item(i));
                    } else {
                         out.print('&');
                         out.print(node.getNodeName());
                         out.print(';');
                    break;
               // print cdata sections
          case Node.CDATA_SECTION_NODE :
                    if (canonical) {
                         out.print(normalize(node.getNodeValue()));
                    } else {
                         out.print("<![CDATA[");
                         out.print(node.getNodeValue());
                         out.print("]]>");
                    break;
               // print text
          case Node.TEXT_NODE :
                    out.print(normalize(node.getNodeValue()));
                    break;
               // print processing instruction
          case Node.PROCESSING_INSTRUCTION_NODE :
                    out.print("<?");
                    out.print(node.getNodeName());
                    String data = node.getNodeValue();
                    if (data != null && data.length() > 0) {
                         out.print(' ');
                         out.print(data);
                    out.print("?>");
                    break;
     if (type == Node.ELEMENT_NODE) {
          out.print("</");
          out.print(node.getNodeName());
          out.print('>');
     out.print("\n");
     out.flush();
} // print(Node)
* Returns a sorted list of attributes
protected Attr[] sortAttributes(NamedNodeMap attrs) {
     int len = (attrs != null) ? attrs.getLength() : 0;
     Attr array[] = new Attr[len];
     for (int i = 0; i < len; i++) {
          array[i] = (Attr) attrs.item(i);
     for (int i = 0; i < len - 1; i++) {
          String name = array[i].getNodeName();
          int index = i;
          for (int j = i + 1; j < len; j++) {
               String curName = array[j].getNodeName();
               if (curName.compareTo(name) < 0) {
                    name = curName;
                    index = j;
          if (index != i) {
               Attr temp = array[i];
               array[i] = array[index];
               array[index] = temp;
     return (array);
regards.

Similar Messages

  • How to modify the xml file

    Hi
    i am able to parse and modify the xml using DOM parser
    after ever modification I am using the below code to write in the file
    org.apache.xml.serialize.OutputFormat format = new org.apache.xml.serialize.OutputFormat(doc);
              format.setIndenting(true);
              org.apache.xml.serialize.XMLSerializer output = new org.apache.xml.serialize.XMLSerializer(new FileOutputStream(xmlFile), format);
              output.serialize(doc);
    using the above code I am overwriting the entire xmlFile
    is there an function that change only the required node the xml that change should me reflected in to the xml file
    thanks in advance

    YoungWinston wrote:
    chi8088 wrote:
    is there an function that change only the required node the xml that change should me reflected in to the xml fileI'm pretty sure there is, but I'm afraid I'm not a DOM expert.No, there is not. An XML file is really at its heart just a text file, and just like you can't simply write a change in the middle of a text file* but rather have to re-write out the entire contents, the same is true for an XML file.
    * unless you use a RandomAccessFile, and know the exact position to seek, and the change doesn't cause the rest of the contents to shift, such as by adding more content or removing some. All of which are very restrictive conditions.

  • Hello Anybody, I have a question. Can any of you please suggest me how to make an xml file from the database table with all the rows? Note:- I am having the XSD Schema file and the resulted XML file should be in that XSD format only.

    Hello Anybody, I have a question. Can any of you please suggest me how to make an xml file from the database table with all the records?
    Note:- I am having the XSD Schema file and the resulted XML file should be in that XSD format only.

    The Oracle documentation has a good overview of the options available
    Generating XML Data from the Database
    Without knowing your version, I just picked 11.2, so you made need to look for that chapter in the documentation for your version to find applicable information.
    You can also find some information in XML DB FAQ

  • How to Merge multiple XML  files in one file ( Env: XML Publisher 5.6.2)

    All,
    I have recently started working on XML publisher and have developed 3 reports in last 2 days using XML Publisher and integrating them with Concurrent programs.
    This is a great tool.
    I have got another requirement, where i need to use xml file generated by multiple run of same report with various parameters and then merge all xml file to a single report. Developing the whole custom process will take very long time and sure will have bugs in it. Instead i was thinking to use xml file generated by Oracle report itself.
    Report "US Gross to net summary" generates xml output in standard output directory and then show output in PDF file. I have 7 such file generated for each payroll. I want to merge output of xml into a single xml so that i can create single report having data from all 7 xml files showing me All payroll output in a single report.
    Can someone please guide me , how can i read xml file data from the output directory of a seeded concurrent program and how to manipulate data in it.
    Thanks
    Ankur

    Hi Tim,
    Thanks for replying. I have looked for "PDFBookBinder class" in xml publisher user guide for ver 5.6.2. I didn't get any reference of this text. Can you please guide me to a tutorial/link where i can get more information about this class.
    Also, i originally thought of similar to your second logic, as my design basis. Oracle process generates the xml file in output directory which i can get. What i didn't get is how do i "pick them up and merge" using publisher. Also, is there way to do this merging process using pl/sql ? Can you please give little more information on your second approach.
    My original plan of action is that i will create a report set in which i will call oracle seeded report for all 7 payrolls in a sequential manner. Then using the child requests of the report set i will get to 7 xml files generated by seeded oracle process. Then the piece i am not sure of , i will use those 7 files to generate a single xml file having payroll name as tree top for each output. Once single xml is ready, i can easily design a template and register the process to generate output as Excel.This process will not require me to actually change any data or do any calculation. It will only reformatting the feilds we see and abiity to see all 7 payroll at one time rather then entering these numbers manually into an excel to do analysis.
    Please provide your feedback, if you think above plan is not feasible or need corrections.
    Best Regards,
    Ankur

  • How to load an XML file to oracle9i server?

    I want to use XSU DBMS_XMLsave package to load an XML file to a relational table using PL/SQL from a distant server. Now, I don't know how to load that XML file to the distant server.
    Somebody help me?

    I want to use XSU DBMS_XMLsave package to load an XML file to a relational table using PL/SQL from a distant server. Now, I don't know how to load that XML file to the distant server.
    Somebody help me?

  • Does anyone know how to convert an XML file to a readable file?

    All,
    I have been using an APP called "SMS Backup & Restore" to backup my message conversations to my Laptop PC.  It works fine BUT the backup file, once in my PC, has an XML extent such as "filename.XML"
    I would like to read and/or print and/or save the text message file so does anyone know how to convert the XML file to something else so it shows all the messages without all the formatting instructions.   
    When I try to see the XML file it shows all the formatting.  If I replace the .XML with .TXT that too shows all the formatting mixed in with the text message narrative.
    When I look at the XML file in SMS Backup & Restore in the Charge phone it looks great showing all the messages just as they were on the phones display.  The problem with this is that there is no way to print or read or save the messages as they appear in the file from the phone itself.  I tried screen capture but if you have, let's say, a 28 message conversation you have to do 7 or 8 screen captures to get them all.
    If only I could convert the XML in my PC to something that is printable or savable or readable that would be the "cats meow."
    Anyone know how???
    JerryF
    PS, You might take a look at my related post.
    https://community.verizonwireless.com/message/809832#809832

    Ann154,
    You were correct again.  I deleted everything I had done to date and re-did the entire SMS backup of my 28 message conversation again and YES I was able to open it using IE-8.  It looks great and it prints great and life is good!  I am going to go make a donation.
    Thanks again for the help.  I marked this thread as answered by you.
    JerryF

  • How to create new XML file using retreived XML content by using SAX API?

    hi all,
    * How to create new XML file using retreived XML content by using SAX ?
    * I have tried my level best, but output is coming invalid format, my code is follows,
    XMLFileParser.java class :-
    import java.io.StringReader;
    import java.io.StringWriter;
    import javax.xml.transform.OutputKeys;
    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.DOMResult;
    import javax.xml.transform.sax.SAXSource;
    import javax.xml.transform.sax.SAXTransformerFactory;
    import javax.xml.transform.sax.TransformerHandler;
    import javax.xml.transform.stream.StreamResult;
    import org.w3c.dom.Document;
    import org.xml.sax.Attributes;
    import org.xml.sax.InputSource;
    import org.xml.sax.SAXException;
    import org.xml.sax.helpers.XMLFilterImpl;
    public class PdfParser extends XMLFilterImpl {
        private TransformerHandler handler;
        Document meta_data;
        private StringWriter meta_data_text = new StringWriter();
        public void startDocument() throws SAXException {
        void startValidation() throws SAXException {
            StreamResult streamResult = new StreamResult(meta_data_text);
            SAXTransformerFactory factory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
            try
                handler = factory.newTransformerHandler();
                Transformer transformer = handler.getTransformer();
                transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
                transformer.setOutputProperty(OutputKeys.INDENT, "yes");
                handler.setResult(streamResult);
                handler.startDocument();
            catch (TransformerConfigurationException tce)
                System.out.println("Error during the parse :"+ tce.getMessageAndLocation());
            super.startDocument();
        public void startElement(String namespaceURI, String localName,
                String qualifiedName, Attributes atts) throws SAXException {
            handler.startElement(namespaceURI, localName, qualifiedName, atts);
            super.startElement(namespaceURI, localName, qualifiedName, atts);
        public void characters(char[] text, int start, int length)
                throws SAXException {
            handler.characters(text, start, length);
            super.characters(text, start, length);
        public void endElement(String namespaceURI, String localName,
                String qualifiedName) throws SAXException {
            super.endElement("", localName, qualifiedName);
            handler.endElement("", localName, qualifiedName);
        public void endDocument() throws SAXException {
        void endValidation() throws SAXException {
            handler.endDocument();
            try {
                TransformerFactory transfactory = TransformerFactory.newInstance();
                Transformer trans = transfactory.newTransformer();
                SAXSource sax_source = new SAXSource(new InputSource(new StringReader(meta_data_text.toString())));
                DOMResult dom_result = new DOMResult();
                trans.transform(sax_source, dom_result);
                meta_data = (Document) dom_result.getNode();
                System.out.println(meta_data_text);
            catch (TransformerConfigurationException tce) {
                System.out.println("Error occurs during the parse :"+ tce.getMessageAndLocation());
            catch (TransformerException te) {
                System.out.println("Error in result transformation :"+ te.getMessageAndLocation());
    } CreateXMLFile.java class :-
    Sax.startDocument();
    Sax.startValidation();
    Sax.startElement("", "pdf", "pdf", new AttributesImpl());
    Sax.startElement("", "basic-metadata", "basic-metadata", new AttributesImpl());          
    String xmp_str = new String(meta_data.getByteArray(),"UTF8");
    char[] xmp_arr = xmp_str.toCharArray();
    Sax.characters(xmp_arr, 0, xmp_arr.length);
    Sax.endElement("", "pdf", "pdf");
    Sax.endValidation();
    Sax.endDocument();
    Sax.endElement("", "basic-metadata", "basic-metadata");* In CreateXMLFile.java
    class, I have retreived the xml content in the meta_data object, after that i have converted into character array and this will be sends to SAX
    * In this case , the XML file created successfully but the retreived XML content added as an text in between basic-metadata Element, that is, retreived XML content
    is not an XML type text, it just an Normal text Why that ?
    * Please help me what is the problem in my code?
    Cheers,
    JavaImran

    Sax.startDocument();
    Sax.startValidation();
    Sax.startElement("", "pdf", "pdf", new AttributesImpl());
    Sax.startElement("", "basic-metadata", "basic-metadata", new AttributesImpl());          
    String xmp_str = new String(meta_data.getByteArray(),"UTF8");
    char[] xmp_arr = xmp_str.toCharArray();
    Sax.characters(xmp_arr, 0, xmp_arr.length);
    </code><code>Sax.endElement("", "basic-metadata", "basic-metadata");</code>
    <code class="jive-code jive-java">Sax.endElement("", "pdf", "pdf");
    Sax.endValidation();
    Sax.endDocument();     
    * I HAVE CHANGED MY AS PER YOUR SUGGESTION, NOW SAME RESULT HAS COMING.
    * I AM NOT ABLE TO GET THE EXACT OUTPUT.,WHY THAT ?
    Thanks,
    JavaImran{code}

  • How to transfer an xml file to NW Portal Knowledge Management from XI?

    Hi all,
    Anybody knows how to transfer an xml file to NW Portal Knowledge Management from XI?
    What kind of adapter type I have to choose? And which procedures I have to do in KM Portal? Create a folder, what kind of folder and permissions?
    Suggestions and ideas are appreciated.
    Thanks in advance,
    Ricardo.

    Hi
    Can anyone tell me how XI sends messages to applications like J2EE. In REceiver comm channel, I think we specify about the target system like J2EE appl.
    Aadapter Type: HTTP
                   Receiver
    Transport Protocol:  HTTP1.0
    Message Protocol:    XI payload in HTTP body
    Adapter Engine:      Integration Server
    Addressing Type:     URL address
    Target host:         localhost
    Service Number:      7001(Port number of Weblogic appl server--where my J2EE appl is deployed).
    Path     :  /Invoke/DisplayRes/
    Authentication Type:Use Logon Data for SAP System
    Content Type: text/xml
    Username:   xiappluser
    password:   xx
    XML code:   UTF-8
    I suppose XI sends msgs to http://localhost:7001/Invoke/DisplayRes/........
    in this example if am correct?
    Then I have given all tyhe necessary setting but my servlet is not able to display XML msg in browser?
    This is my servlet code:
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
         PrintWriter out = response.getWriter();
         BufferedReader brin =new BufferedReader(new InputStreamReader(request.getInputStream()));
         String inputLine;
         StringBuffer sBuf = new StringBuffer();
            response.setContentType("text/xml");
         while ((inputLine = brin.readLine()) != null)
             sBuf.append(inputLine);
             out.println("hi");            
                out.println(sBuf.toString());
             brin.close();
             out.flush();
    What went wrong?
    Help me, all helpful answers are highly rewarded.
    Thanks

  • How to transfer a xml file?

    Dear friends,
    I have a question about how to transfer a xml file between server and client using axis or weblogic.
    My application needs to send xml files instead of primitive data types and bean objects.
    Is it possible to tranfer files between server and client?
    thank you very much for your great help!
    jayanandan.

    hi,
    There are two ways in which u can send an xml file.
    1) U send it along with the body of the soap message.
    2)u can send it as an attachment in the soap envelope. this method u can use for any type of files.
    If u send it in soap body the it will take more time for the processing of the soap body.so attachment is the best way.
    I case of any queries please feel free to post it in the forum
    Regards
    Sandy

  • How to get the XML file if we are using the Product short name.

    Hi,
    Till now I have used Short name of the Concurrent Program for Code while creating a Data Definition. Now saw a seeded template which has given the Code by Product short name. If we have the concurrent program then it is easy to refer the fields by checking the XML file. In this case how to find the XML file or how to refer all the fields if we have given code with Product short name. I saw this for iReceivables(ARI). Anybody please help me.
    Thanks.

    Hi Siva
    Just to clarify, rather than the short name of the conc program there is a shipped data definition that just uses the product short name? What is the data def so I can check it.
    Regards, Tim

  • How to read an xml file from headers

    Hi ,
    I am not getting how to read an xml file sent by client device in header to server.
    Thankx.

    There is a getHeader() in HttpServletRequest interface
    String locationURL=request.getHeader("Location");If URL of your file was set in Location attribute of header.
    Edited by: ngpgeeta on Dec 19, 2008 8:03 AM

  • How to generate an XML file for an animation of IK armature

    Can someone please tell me how to generate an XML file for an animation of IK armature.
    I have a 5 keyframe/16 frame animation of a human character made up of a series of moveiclip symbols that is animated with an IK armature.  I need the XML information from the animation. 
    When I go to Commands > Export Motion XML I get the error message "There is more than one object on frame 1" and then nothing happens.
    Thank you,
    c

    I hope that's not the case.  I want to write to adobe about it.  I think it's a great feature and it functions really well even though it is not a very developed IK tool.  My biggest issue with it is ouput options and integration with motion tweens.
    I have seen a lot of examples of animators using it online, just no one talked about output.  I just feel it hasn't been developed.  It can generate a sprite sheet but only for a single pose frame of the animation, and not all the key frames or pose tweens.  I find that functionality quite odd, as if adobe just forgot about IK when added in sprite sheets, etc. and the reason it half works is just an accident.

  • How to call the XML file as PrivateResourcePath in JSP

    Hi All,
    I want to call the layer-config.xml values in JSP dropdown list. How to call the XML file as PrivateResourcePath in JSP... please advise me if any solution.
    locaiton: dist/PORTAL-INF/layer-config.xml
      <?xml version="1.0" encoding="utf-8" ?>
    - <layer-config>
    - <system>
      <layer>Test</layer>
      <internal>true</internal>
      </system>
    - <system>
      <layer>Test1</layer>
      <internal>false</internal>
      </system>
    - <system>
      <layer>Test3</layer>
      <internal>false</internal>
      </system>
      </layer-config>
    Thanks in advance.

    Hi,
    The below link may help you.
    [Accessing image from dist/imgaes folder inside JSPDynpage Component;
    Regards,
    Suresh Bachimanchi

  • How to read a xml file in ActionScript

    In mxml we can find <mx:Model> to load a xml and using
    it easily. But in ActionScript, there is no such a Class about this
    function(only implemented in mxml), so how to load a xml file in a
    easy way in ActionScript?
    And I tried using HTTPService, but I think that is not the
    best solution because the code do not know when the hander get the
    data in xml then the function return that value.
    So please someone give a easy way as <mx:model> in mxml
    to read the xml file?
    Thank you very much.

    Flex is asynchronous so HTTPService with result event handler
    is the way to go.

  • How to import a XML file into the document?

    Hai,
    i had created a table using xml file....
    Now i want to import that xml file tabel into the document...
    Can any one tell me how to import the xml file into the document?
    thanks
    senthil

    Hai...
    this is senthil...
    i'm beginner for creating adobe indesign plugins..
    i want to import a html file in the document...
    i want to create a table by using html tags and
    that table will be imported into the document..
    How shall i do it?
    can any one plzz explain me?

Maybe you are looking for

  • FORM and JSP in the same page

    Hello All Is it possible to pass variable from a html textbox to a JSP? but they both are in the same page. For this purpose, I have a created a index.html, which contain two frames, top.html and bottom.jsp. There is a textbox in the top.html, it col

  • How to get actio type in HR MODULE (Fired) from PA40

    Hello Experts i am trying to implement the user exit  EXIT_SAPMP50A_001 when the KEY USER try to make and FIRED so and i need to have the action type for make and evaluation but i can´t get it.. i have already implemented the EXIT_SAPLRPAI_001 but th

  • JTable display problem..

    Hi all! umm.. i'm a student.. so bare with me hehe i'm creating a jTable inside a jScrollPane because it doesnt fit in the window... when i scroll to the right, to see the rest of the table, the column title blurs like the last pixels seen on the bor

  • HT1420 I need to change my security questions. How do I do this?

    How do I change my security questions?

  • IE, ActiveX and installing Flash Player

    I'm stuck in a loop. I hit a page that reqires the flash player and it doesn't show the content. Then I install the flash player, then it tells me it needs activeX. I try to install that and it never works. It keeps prompting me to install ActiveX...