Changing /updating an xml file using JAXP(DOM)

Hello,
i am fairly new to xml and am using it in my degree project.I am able to retrieve and read data from a fairly large xml file using JAXP(DOM) and/or XMLBeans.I am having difficulties in updating the xml document. Any updation i believe is ito be saved into a new xml document,but dont know how to proceed with it. Any help would be appreciated.
Following is a snippet of my code using JAXP. Here i am able to retrieve data from the source file.
File document=new File("C:\\tester.xml");
try {
DocumentBuilderFactory factory
= DocumentBuilderFactory.newInstance();
DocumentBuilder parserr = factory.newDocumentBuilder();
Document doc=parserr.parse(document);
System.out.println(document + " is well-formed.");
NodeList n2=doc.getElementsByTagName("Top");
NodeList n3=doc.getElementsByTagName("Base");
int x=n2.getLength();
System.out.println("There are " x "players");
for(int g=0;g<=x;g++)
System.out.println("Top is" + n2.item(g).getFirstChild().getNodeValue()+" Base is" +n3.item(g).getFirstChild().getNodeValue());
--------------------------------------------------------------------------------

Following is my updation code to the dom tree:
NodeList list=doc.getElementsByTagName("Information");
for(int i=0; i<list.getLength();i++){
Node thissampnode=list.item(i);
Node thisNameNode=thissampnode.getFirstChild();
if(thisNameNode==null) continue;
if(thisNameNode.getFirstChild()==null)continue;
// if(thisNameNode.getFirstChild() !(instanceof org.w3c.dom.Text) continue;
String data=thisNameNode.getFirstChild().getNodeValue();
if (! data.equals("0.59")) continue;
Node newsampNode = doc.createElement("Samp");
Node newsampTopNode = doc.createElement("Top");
Text tnNode = doc.createTextNode("0.50");
newsampTopNode.appendChild(tnNode);
Element newsampRef = doc.createElement("Ref");
Text tsr = doc.createTextNode("0");
newsampRef.appendChild(tsr);
Element newsampType = doc.createElement("Type");
Text tt = doc.createTextNode("z");
newsampType.appendChild(tt);
Element newsampbase = doc.createElement("Base");
Text sb = doc.createTextNode("0.55");
newsampbase.appendChild(sb);
newsampNode.appendChild(newsampTopNode);
newsampNode.appendChild(newsampRef);
newsampNode.appendChild(newsampType);
newsampNode.appendChild(newsampbase);
rootNode.insertBefore(newsampNode, thissampnode);
Here i dont see any changes to the original xml source file.

Similar Messages

  • Update the xml file using jsp

    Hi all,
    I want to update the xml file node values.I tried this but the node values is not updating ie not changing
    This is my code
    This my jsp page
    <%@page contentType="text/html"%>
    <%@page pageEncoding="UTF-8"%>
    <%@ page import="javax.xml.parsers.DocumentBuilderFactory,
    javax.xml.parsers.DocumentBuilder,org.w3c.dom.*,org.w3c.dom.Element"
    %>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
    </head>
    <body>
    <%try
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse("http://localhost:8084/XmlApplication1/sss.xml");
    String name = "Banglore";
    NodeList nlst = doc.getElementsByTagName("name");
    Node node= nlst.item(0).getFirstChild();
    // Node nod2=node.getFirstChild();
    node.setNodeValue(name);
    catch(Exception e)
    out.println(e) ;
    %>
    This is my xml file
    <?xml version="1.0" encoding="UTF-8"?>
    <place>
    <name>chennai</name>
    </place>
    plz do some help to update this value

    i tried this but the data is just transfereinf in xml file but its not over writet he content in xml file.
    i send my code
    <%@page contentType="text/html"%>
    <%@page pageEncoding="UTF-8"%>
    <%@ page import="javax.xml.parsers.DocumentBuilderFactory,
    javax.xml.parsers.DocumentBuilder,org.w3c.dom.*,org.w3c.dom.Element"
    %>
    <%@ page import=" org.w3c.dom.*,java.io.File,java.io.IOException,java.io.OutputStream,java.io.FileOutputStream,
    javax.xml.parsers.*,
    javax.xml.transform.*,
    javax.xml.transform.dom.*,
    javax.xml.transform.stream.*
    " %>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
    </head>
    <body>
    <%
    String bgcolor = request.getParameter("bgcolor");
    String heading = request.getParameter("heading");
    String fontsize = request.getParameter("fontsize");
    String fontcolor = request.getParameter("fontcolor");
    String str1="";
    String str2="";
    try{
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse("http://localhost:8084/XmlApplication1/input.xml");
    Document tempDocument = doc;
    DOMSource source = new DOMSource(tempDocument);
    NodeList n11 = doc.getElementsByTagName("bgcolor");
    Node n1= n11.item(0).getFirstChild();
    str1 = n1.getNodeValue();
    out.println(str1);
    n1.setNodeValue(bgcolor);
    out.println("After change");
    str2 = n1.getNodeValue();
    out.println(str2);
    NodeList n12 = doc.getElementsByTagName("heading");
    Node n2= n12.item(0).getFirstChild();
    String str11 = n2.getNodeValue();
    out.println(str11);
    n2.setNodeValue(heading);
    out.println("After change");
    String str22 = n2.getNodeValue();
    out.println(str22);
    NodeList n13 = doc.getElementsByTagName("fontsize");
    Node n3= n13.item(0).getFirstChild();
    String str13 = n3.getNodeValue();
    out.println(str13);
    n3.setNodeValue(fontsize);
    out.println("After change");
    String str23 = n3.getNodeValue();
    out.println(str23);
    NodeList n14 = doc.getElementsByTagName("fontcolor");
    Node n4= n14.item(0).getFirstChild();
    String str14 = n4.getNodeValue();
    out.println(str14);
    n4.setNodeValue(fontcolor);
    out.println("After change");
    String str24 = n4.getNodeValue();
    out.println(str24);
    // File file = new File("D:/Leela/XmlApplication1/build/web/input.xml");
    OutputStream outStream = new FileOutputStream("D:/Leela/XmlApplication1/build/web/input.xml");
    StreamResult result = new StreamResult(outStream);
    Transformer xformer = TransformerFactory.newInstance().newTransformer();
    System.out.println("Wrote to new file");
    xformer.transform(source, result);
    outStream.flush();
    outStream.close();
    catch(Exception e)
    out.println();
    %>
    </body>
    </html>
    the xml file shows the same content its not ovwr writing
    <?xml version="1.0" encoding="UTF-8"?>
    <input>
    <bgcolor>DarkCyan</bgcolor>
    <heading>4</heading>
    <fontsize>12</fontsize>
    <fontcolor>DodgerBlue</fontcolor>
    </input>

  • Parsing an xml file using xerces DOM  parser

    Hi
    I want to parse a simple xml file using DOM parser.
    The file is
    <Item>
         <SubItem>
              <title>SubItem0</title>
              <attr1>0</attr1>
              <attr2>0</attr2>
              <attr3>0</attr3>
         </SubItem>
         <SubItem>
              <title>SubItem1</title>
              <attr1>1</attr1>
              <attr2>0</attr2>
              <attr3>0</attr3>
         </SubItem>
         <SubItem>
              <title>SubItem2</title>
              <attr1>1</attr1>
              <attr2>1</attr2>
              <attr3>0</attr3>
              <SubItem>
                   <title>SubItem20</title>
                   <attr1>2</attr1>
                   <attr2>1</attr2>
                   <attr3>0</attr3>
              </SubItem>
              <SubItem>
                   <title>SubItem21</title>
                   <attr1>1</attr1>
                   <attr2>1</attr2>
                   <attr3>0</attr3>
              </SubItem>
         </SubItem>
    </Item>
    I just want to parse this file and want to store the values in desired datastructures,
    I am trying using DOM parser, since it gives a tree structure, which is ok in this case.
    public void init()
              InputReader ir     =new InputReader("Habsys");
              Document      doc     =ir.read("Habitat");
              System.out.println(doc);
              traverse(doc);
    private void traverse(Document idoc)
              NodeList lchildren=idoc.getElementsByTagName("SubItem");
              for(int i=0;i<lchildren.getLength();i++)
                   String lgstr=lchildren.item(i).getNodeName();
                   if(lgstr.equals("SubItem"))
                        traverse(lchildren.item(i));
    private void traverse (Node node) {
    int type = node.getNodeType();
    if (type == Node.ELEMENT_NODE)
    System.out.println ("Name :"+node.getNodeName());
    if(!node.hasChildNodes())
    System.out.println ("Value :"+node.getNodeValue());
    NodeList children = node.getChildNodes();
    if (children != null) {
    for (int i=0; i< children.getLength(); i++)
    traverse (children.item(i));
    But I am not getting required results, a lot of values I am getting as null
    Could anybody tell me how to retrieve the data from the xml file, I simply want to read data and store it in data structures. For eg, for tag Subitem with title as ' SubItem1' has attr1 as '1', attr2 as'0' and attr3 as '0'.
    Thanks
    Gaurav

    Check This Sample Code....
    public void amethod(){
    DocumentBuilderFactory dbf = null;
    DocumentBuilder docBuilder = null;
    Document doc = null;
    try{
         dbf = DocumentBuilderFactory.newInstance();
         db = dbf.newDocumentBuilder();
         doc = db.parse(New File("path/to/your/file"));
         Node root = doc.getDocumentElement();
         System.out.println("Root Node = " + root.getNodeName());
         readNode(root);
    }catch(FactoryConfigurationError fce){ fce.printStackTrace();
    }catch(ParserConfigurationException pce){  pce.printStackTrace();
    }catch(IOException ioe){  ioe.printStackTrace();
    }catch(SAXException saxe){  saxe.printStackTrace();
    private void readNode(Node node) {
    System.out.println("Current Node = " + node.getNodeName());
    readAttributes(node);
    readChildren(node);
    private void readAttributes(Node node) {
    if (!node.hasAttributes())
         return;
    System.out.println("Attributes:");
    NamedNodeMap attrNodes = node.getAttributes();
    for (int i=0; i<attrNodes.getLength(); i++) {
    Attr attr = (Attr)attrNodes.item(i);
    System.out.println(attr.getNodeName() + " => " + attr.getNodeValue());
    private void readChildren(Node node) {
    if (!node.hasChildNodes())
         return;
    System.out.println("Value/s:");
    NodeList childNodes = node.getChildNodes();
    for (int i=0; i<childNodes.getLength(); i++) {
    Node child = (Node)childNodes.item(i);
    if (child.getNodeType() == Node.ELEMENT_NODE) {
    readNode(child);
    continue;
    if (child.getNodeType() == Node.TEXT_NODE) {
    if (child.getNodeValue()!=null)
    System.out.println(child.getNodeValue());

  • How to Update existing XML File Using Java Swing

    Hi,
    I am reading XML file and getting keywords into JList. When i add some keywords into JList through textfield and remove keywords JList, then after click on save button it should update xml file. How can i do it ?
    Please provide me some code tips for updating xml file
    This is the code that i am using for reading XML File:
    import javax.swing.*;
    import java.awt.event.*;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.NodeList;
    import org.xml.sax.SAXException;
    import java.io.IOException;
    import java.util.*;
    import java.text.Collator;
    import java.util.regex.*;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import com.cloudgarden.layout.AnchorConstraint;
    import com.cloudgarden.layout.AnchorLayout;
    public class getKeywords extends JFrame implements ActionListener
    static JPanel p;
    static JLabel lbl;
    static JButton btnSave,btnAdd,btnRemove;
    static String path;
    static Vector v;
    static JList lstCur;
    static JTextField txtKey;
    Document dom;
    static image imgval;
    NodeList nodelstImage;
    static AnchorLayout anchorLay;
    private DefaultListModel lstCurModel;
    public getKeywords()
         super("Current Keywords");
        v=new Vector();
        p=new JPanel();
        txtKey=new JTextField(10);
        btnAdd=new JButton("Add");
        btnRemove=new JButton("Remove");
        btnSave=new JButton("Save");
        lbl=new JLabel("Current Keywords");
        lstCurModel=new DefaultListModel();
            lstCur=new JList();
            JScrollPane scr=new JScrollPane(lstCur);
        runExample();
         lstCur.setModel(lstCurModel);
         p.add(lbl);
         p.add(scr);
         p.add(txtKey);
         p.add(btnAdd);
         p.add(btnRemove);
         p.add(btnSave);
         add(p);
         btnAdd.addActionListener(this);
         btnRemove.addActionListener(this);
         btnSave.addActionListener(this);
         setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    public static void main(String arg[])
         getKeywords g=new getKeywords();
         g.resize(250,400);
         g.setVisible(true);     
    public void actionPerformed(ActionEvent ae)
         if(ae.getSource()==btnAdd)
              lstCurModel.addElement(txtKey.getText());
         if(ae.getSource()==btnRemove)
              lstCurModel.remove(lstCur.getSelectedIndex());
         if(ae.getSource()==btnSave)
              //Code to Write
         public void runExample()
              //Parse the XML file and get the DOM object
              ParseXMLFile();
              //Get the Detail of the Image Document
              parseImageDocument();
              //Get the Detail of the LML Document
              //parseLMLDocument();
              //System.out.println(lmlval.Title);
         public void ParseXMLFile()
              //Get the Factory
              DocumentBuilderFactory builderFac = DocumentBuilderFactory.newInstance();
              try
                   //Using factory get an instance of the Document Builder
                   DocumentBuilder builder = builderFac.newDocumentBuilder();
                   //parse using builder to get DOM representation of the XML file
                   dom = builder.parse("LML.xml");
              catch(ParserConfigurationException pce)
                   pce.printStackTrace();
              catch(SAXException sax)
                   sax.printStackTrace();
              catch(IOException ioex)
                   ioex.printStackTrace();
         public void parseImageDocument()
              //Get the root element
              Element docImgEle = dom.getDocumentElement();
              //Get a nodelist for <Image> Element
              nodelstImage =  docImgEle.getElementsByTagName("Image");
              if(nodelstImage != null && nodelstImage.getLength() > 0)
                   for(int i = 0; i < nodelstImage.getLength(); i++)
                        //Get the LML elements
                        Element el = (Element)nodelstImage.item(i);
                        //Get the LML object
                        getImage myImgval = new getImage();
                        imgval = myImgval.getimage(el);
                        v.addElement(new String(imgval.Thumb));
                        String[] x = Pattern.compile(",").split(imgval.Keys);
                        for (int s=0; s<x.length; s++)
                        lstCurModel.addElement(x[s].trim());
                        //System.out.println(x[s].trim());
    }     Thanks
    Nitin

    You should update your DOM document to represent the changes that you want made.
    Then, using the Transformation API you simply transform your document onto a stream representing your file. Something like this:
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    // TODO - set indentation amount!
    Source source = new DOMSource(dom);
    Result result = new StreamResult(file);
    transformer.transform(source, result);Hope this helps.

  • Updating XML file using DOM parser

    Hi,
    Can someone help me, how to update following XML file using DOM parser.
    The following is my XML file.
    <students>
         <student>
              <id>1</id>
              <name>abc</name>
         </student>
         <student>
              <id>2</id>
              <name>xyz</name>
         </student>
         <student>
              <id>3</id>
              <name/>
         </student>
         <student>
              <id>4</id>
              <name>ijk</name>
         </student>
         <student>
              <id>5</id>
              <name></name>
         </student>
    </students>Consider, I will input 2 fields, ie., id & name. For the matching Id, the name has to be updated.
    Though, I have achieved this, but I am unable to update the value for 3rd record, & 5th record ie., id=3 & id=5. Since, these are blank.
    Thanks.

    Some <name> elements have a child node which is a text node. From what you say it appears you know how to change those text nodes.
    The other <name> elements don't have any child nodes. But you want one. This suggests to me that you need code that creates a text node and adds it to the <name> element as its child.

  • How to update the value in xml file using transformer after setNodeValue

    Hi,
    This is my code
    I want to set update the values in xml file using transformer..
    Any one can help me
    This is my Xml file
    <?xml version="1.0" encoding="UTF-8"?>
    <place>
    <name>chennai</name>
    </place>
    Jsp Page
    <%@page contentType="text/html"%>
    <%@page pageEncoding="UTF-8"%>
    <%@ page import="javax.xml.parsers.DocumentBuilderFactory,
    javax.xml.parsers.DocumentBuilder,org.w3c.dom.*,org.w3c.dom.Element"
    %>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
    </head>
    <body>
    <% String str="";
    String str1="";
    try
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse("http://localhost:8084/XmlApplication1/sss.xml");
    out.println("Before change");
    NodeList n11 = doc.getElementsByTagName("name");
    Node n22= n11.item(0).getFirstChild();
    str1 = n22.getNodeValue();
    out.println(str1);
    out.println("After change");
    String name = "Banglore";
    NodeList nlst = doc.getElementsByTagName("name");
    Node node= nlst.item(0).getFirstChild();
    node.setNodeValue(name);
    NodeList n1 = doc.getElementsByTagName("name");
    Node n2= n1.item(0).getFirstChild();
    str = n2.getNodeValue();
    out.println(str);
    catch(Exception e)
    out.println(e) ;
    %>
    <h1><%=str%></h1>
    <%--
    This example uses JSTL, uncomment the taglib directive above.
    To test, display the page like this: index.jsp?sayHello=true&name=Murphy
    --%>
    <%--
    <c:if test="${param.sayHello}">
    <!-- Let's welcome the user ${param.name} -->
    Hello ${param.name}!
    </c:if>
    --%>
    </body>
    </html>

    hi check this exit...
    IWO10012

  • How to update XML file using XSLT

    Hi there,
    I have a "small" issue with exporting data to an XML file using XSLT.
    A two steps process is needed to import data from a non-hierarchical XML file into ABAP, change the data, and then update the XML file with new values. The problem is not trivial, since the format of the XML file is a complex one: there are many interdependent elements on the same level, pointing to each other by using id and ref attributes. Based on these values the data can be read and written into an internal table. I use XSLT and XPath for that. So the inbound process is done and seems to work correctly. I have to mention that the file contains much more data than I need. I am working only with a small part of it.
    Now the changed data must be exported back into the XML file, meaning that the content of certain elements must be updated. How can this be done with XSLT? I can pass only the internal table to the transformation, so how do I access the XML file in order to update it? I have tried to use the <B>xsl:document()</B> function to access the content of the file store locally on my PC, but it fails each time by throwing and URI exception. I have tried the absolute path without any addition and the path with the file:/// addition. Same result. Please advise.
    Many thanks,
    Ferenc
    P.S. Please provide me with links only if they are relevant for this very matter. I will not give points for irrelevant postings...

    Now the changed data must be exported back into the XML file, meaning that the content of certain elements must be updated. How can this be done with XSLT?
    XSLT approach:  check these online tutorial
    http://www.xml.com/pub/a/2000/08/02/xslt/index.html
    http://www.xml.com/pub/a/2000/06/07/transforming/index.html
    ABAP approach:
    for example you have the xml (original) in a string called say xml_out .
    data: l_xml  type ref to cl_xml_document ,
            node type ref to if_ixml_node  .
    create object l_xml.
    call method l_xml->parse_string
      exporting
        stream = xml_out.
    node = l_xml->find_node(
        name   = 'IDENTITY'
       ROOT   = ROOT
    l_xml->set_attribute(
        name    = 'Name'
        value   = 'Charles'
        node    = node
    (the above example reads the element IDENTITY and sets attribute name/value to the same)
    like wise you can add new elements starting from IDENTITY using various methods available in class CL_XML_DOCUMENT
    so how do I access the XML file in order to update it?
    you have already read this XML into a ABAP variable right?
    Sorry couldnt understand your whole process, why do you need to read local XML file?
    Raja

  • Problem writing xml file using DOM

    Hi,
    I am trying to write a xml file using DOM. I am using xalan 2.5, xerces 1.4.4, jdk 1.3.1 in JRun 3 on windows.
    The code where I get exception :
                   TransformerFactory tFactory = TransformerFactory.newInstance();
                   Transformer transformer = tFactory.newTransformer();
                   transformer.transform(new DOMSource(doc), new StreamResult("pr.xml"));
    I get the runtime error as follows:
    javax.servlet.ServletException: null
    java.lang.NoSuchMethodError
         at org.apache.xml.utils.DOM2Helper.getNamespaceOfNodeDOM2Helper.java:342)
         at org.apache.xml.utils.TreeWalker.startNode(TreeWalker.java:387)
         at org.apache.xml.utils.TreeWalker.traverse(TreeWalker.java:202)
         at org.apache.xalan.transformer.TransformerIdentityImpl.transform(TransformerIdentityImpl.java:343)
    Thinking it is because of classpath, I placed xalan 2.5, xerces 1.4.4 jar files in jrun admin lib directory and in server lib directory as well. Still getting the same error.
    Any suggestion?
    Thanks in advance

    xalan is included in JRun 4. However JRun 3 does not.
    However I tried with the same code in JRun3 in different system. The error is completely different. I understand this is because of different version of files. trying to solve ;)
    Here my new exception
    javax.servlet.ServletException: org/w3c/dom/ranges/DocumentRange
    java.lang.NoClassDefFoundError: org/w3c/dom/ranges/DocumentRange
         at java.lang.ClassLoader.defineClass0(Native Method)
         at java.lang.ClassLoader.defineClass(ClassLoader.java:493)
         at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:111)
         at java.net.URLClassLoader.defineClass(URLClassLoader.java:248)
         at java.net.URLClassLoader.access$100(URLClassLoader.java:56)
         at java.net.URLClassLoader$1.run(URLClassLoader.java:195)
         at java.security.AccessController.doPrivileged(Native Method)
         at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
         at java.lang.ClassLoader.loadClass(ClassLoader.java:299)
         at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:286)
         at java.lang.ClassLoader.loadClass(ClassLoader.java:255)
         at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:315)
         at java.lang.ClassLoader.defineClass0(Native Method)
         at java.lang.ClassLoader.defineClass(ClassLoader.java:493)
         at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:111)
         at java.net.URLClassLoader.defineClass(URLClassLoader.java:248)
         at java.net.URLClassLoader.access$100(URLClassLoader.java:56)
         at java.net.URLClassLoader$1.run(URLClassLoader.java:195)
         at java.security.AccessController.doPrivileged(Native Method)
         at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
         at java.lang.ClassLoader.loadClass(ClassLoader.java:299)
         at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:286)
         at java.lang.ClassLoader.loadClass(ClassLoader.java:255)
         at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:315)
         at org.apache.xerces.jaxp.DocumentBuilderImpl.(Unknown Source)
         at org.apache.xerces.jaxp.DocumentBuilderFactoryImpl.newDocumentBuilder(Unknown Source)
         at com.cybell.appl.deliveryorder.cmd.CreateXMLDOFile.createFile(CreateXMLDOFile.java:73)
         at com.cybell.appl.deliveryorder.cmd.CreateXMLDOFile.execute(CreateXMLDOFile.java:36)
         at com.cybell.appl.framework.cmd.BaseCommand.start(BaseCommand.java:50)
         at com.cybell.appl.framework.control.BaseController.service(BaseController.java:38)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:865)
         at allaire.jrun.servlet.JRunSE.service(../servlet/JRunSE.java:1013)
         at allaire.jrun.servlet.JRunSE.runServlet(../servlet/JRunSE.java:925)
         at allaire.jrun.servlet.JRunNamedDispatcher.forward(../servlet/JRunNamedDispatcher.java:34)
         at allaire.jrun.servlet.Invoker.service(../servlet/Invoker.java:84)
         at allaire.jrun.servlet.JRunSE.service(../servlet/JRunSE.java:1013)
         at allaire.jrun.servlet.JRunSE.runServlet(../servlet/JRunSE.java:925)
         at allaire.jrun.servlet.JRunRequestDispatcher.forward(../servlet/JRunRequestDispatcher.java:88)
         at allaire.jrun.servlet.JRunSE.service(../servlet/JRunSE.java:1131)
         at allaire.jrun.servlet.JvmContext.dispatch(../servlet/JvmContext.java:330)
         at allaire.jrun.http.WebEndpoint.run(../http/WebEndpoint.java:107)
         at allaire.jrun.ThreadPool.run(../ThreadPool.java:272)
         at allaire.jrun.WorkerThread.run(../WorkerThread.java:75)

  • How to edit/update data into an XML file using Flex and Actionscript

    I can read an external xml file, please see the code below:
    protected function button1_clickHandler(event:MouseEvent):void
    var GrowthChartsDataGrid:XML;
    var loader:URLLoader = new URLLoader();
    var request:URLRequest = new URLRequest("../GrowthChartsDataGrid.xml");
        loader.load(request);
        loader.addEventListener(Event.COMPLETE, onComplete)
    function onComplete (event:Event)
         var loader:URLLoader = URLLoader(event.target);
         GrowthChartsDataGrid = new XML(loader.data);
         GrowthChartsDataGrid.GrowthChartGridView += <Month> {txtMonth.text} <Weight> {txtWeight.text} </Weight> </Month>
         texttesting.text = GrowthChartsDataGrid.toString();
    I can read an XML file and can add an extra node and can display it in a text filed. But I want to update the XML file contents which will come from the txtMonth and txtWeight text boxes.
    Please any suggestions???

    First of all thanks for your quick reply .
    I actually want to add another node inthe xml file. Files is at a local location and i can read the file and add an extra node (but I cant store this extra node in the actual XML file). But I want to save XML with the extra node.
    For exmaple,
    my current xml is:
    <?xml version="1.0" encoding="utf-8"?>
    <GrowthChartGridView>
        <Month> 1
        <Weight>3.5</Weight></Month>
    <Month> 2
        <Weight>3.9</Weight></Month>
    <Month> 3
        <Weight>4.5</Weight></Month>
    </GrowthChartGridView>
    and at run time, I can create a new node using the data from two textboxes at button click event.
         GrowthChartsDataGrid.GrowthChartGridView += <Month> {txtMonth.text} <Weight> {txtWeight.text} </Weight> </Month>
    Now what I want to do is, I want to add this node back in to my XML. Therefore, the result I am looking for is, my local XML should update like this.
    <?xml version="1.0" encoding="utf-8"?>
    <GrowthChartGridView>
        <Month> 1
        <Weight>3.5</Weight></Month>
    <Month> 2
        <Weight>3.9</Weight></Month>
    <Month> 3
        <Weight>4.5</Weight></Month>
    <Month> {txtMonth.text} <Weight> {txtWeight.text} </Weight> </Month>  //I can read data from text boxes so its fine but I can not store this in to                                                                                                          my original XML
    </GrowthChartGridView>
    Thanks

  • [svn] 3037: Update flex-config. xml files used by the team and qa webapps to use the {targetPlayerMajorVersion} token instead of a hardcoded player version in the library-path and external-library-path .

    Revision: 3037
    Author: [email protected]
    Date: 2008-08-29 06:54:15 -0700 (Fri, 29 Aug 2008)
    Log Message:
    Update flex-config.xml files used by the team and qa webapps to use the {targetPlayerMajorVersion} token instead of a hardcoded player version in the library-path and external-library-path. This will allow the correct playerglobal.swc to be located when the target player version is set in the flex-config.xml or passed to mxmlc or compc.
    Modified Paths:
    blazeds/trunk/apps/team/WEB-INF/flex/flex-config.xml
    blazeds/trunk/qa/resources/config/flex-config.xml

    Unfortunately I don't have the
    "org.eclipse.swt.win32.win32.x86_3.1.2.jar" file. On my computer
    the folder is not set up the same way (C:\Program Files\Adobe\Flex
    Builder 2\plugins) instead it is set up as (C:\Program
    Files\Adobe\Flex Builder 2\metadata\plugins) but I've looked in
    everything and that file just isn't in there. I've re downloaded it
    twice. Still not there. Is there anything else i can do.

  • Reading XML file using BAPI and then uploading that xml file data into SAP

    I am getting a xml file from Java server. I need to take
    data from this file using BAPI and need to upload into SAP using SAP.
    Please tell me how to read XML files using BAPI's.

    <b>SDIXML_DATA_TO_DOM</b> Convert SAP data (elementary/structured/table types) into DOM (XML
    <b>SDIXML_DOM_TO_XML</b>  Convert DOM (XML) into string of bytes that can be downloaded to PC or application server
    <b>SDIXML_DOM_TO_SCREEN</b> Display DOM (XML)
    <b>SDIXML_DOM_TO_DATA</b>
    data: it_table like t001 occurs 0.
    data: l_dom      TYPE REF TO IF_IXML_ELEMENT,
          m_document TYPE REF TO IF_IXML_DOCUMENT,
          g_ixml     TYPE REF TO IF_IXML,
          w_string   TYPE XSTRING,
          w_size     TYPE I,
          w_result   TYPE I,
          w_line     TYPE STRING,
          it_xml     TYPE DCXMLLINES,
          s_xml      like line of it_xml,
          w_rc       like sy-subrc.
    start-of-selection.
      select * from t001 into table it_table.
    end-of-selection.
    initialize iXML-Framework          ****
      write: / 'initialiazing iXML:'.
      class cl_ixml definition load.
      g_ixml = cl_ixml=>create( ).
      check not g_ixml is initial.
      write: 'ok'.
    create DOM from SAP data           ****
      write: / 'creating iXML doc:'.
      m_document = g_ixml->create_document( ).
      check not m_document is initial.
      write: 'ok'.
      write: / 'converting DATA TO DOM 1:'.
      CALL FUNCTION 'SDIXML_DATA_TO_DOM'
        EXPORTING
          NAME               = 'IT_TABLE'
          DATAOBJECT         = it_table[]
        IMPORTING
          DATA_AS_DOM        = l_dom
        CHANGING
          DOCUMENT           = m_document
        EXCEPTIONS
          ILLEGAL_NAME       = 1
          OTHERS             = 2.
      if sy-subrc = 0.  write  'ok'.
      else.             write: 'Err =', sy-subrc.
      endif.
      check not l_dom is initial.
      write: / 'appending DOM to iXML doc:'.
      w_rc = m_document->append_child( new_child = l_dom ).
      if w_rc is initial.  write  'ok'.
      else.                write: 'Err =', w_rc.
      endif.
    visualize iXML (DOM)               ****
      write: / 'displaying DOM:'.
      CALL FUNCTION 'SDIXML_DOM_TO_SCREEN'
        EXPORTING
          DOCUMENT          = m_document
        EXCEPTIONS
          NO_DOCUMENT       = 1
          OTHERS            = 2.
      if sy-subrc = 0.  write  'ok'.
      else.             write: 'Err =', sy-subrc.
      endif.
    convert DOM to XML doc (table)     ****
      write: / 'converting DOM TO XML:'.
      CALL FUNCTION 'SDIXML_DOM_TO_XML'
        EXPORTING
          DOCUMENT            = m_document
        PRETTY_PRINT        = ' '
        IMPORTING
          XML_AS_STRING       = w_string
          SIZE                = w_size
        TABLES
          XML_AS_TABLE        = it_xml
        EXCEPTIONS
          NO_DOCUMENT         = 1
          OTHERS              = 2.
      if sy-subrc = 0.   write  'ok'.
      else.              write: 'Err =', sy-subrc.
      endif.
      write: / 'XML as string of size:', w_size, / w_string.
      describe table it_xml lines w_result.
      write: / 'XML as table of', w_result, 'lines:'..
      loop at it_xml into s_xml.
        write s_xml.
      endloop.
      write: / 'end of processing'.
    end of code
    Hope this will be useful.
    regards
    vinod

  • 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 write as XML file using java 1.5

    hi all,
    i am trying to create an XML file using java 1.5. I took a XML creating java file which was working with java 1.4 and ported same file into java 1.5 with changes according to the SAX and DOM implmentation in java 1.5 and tried to compile. But while writing as a file it throws error "cannot find the symbol."
    can any body help me out to solve this issue.......
    thankx in advance
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import org.w3c.dom.NamedNodeMap;
    import org.xml.sax.SAXException;
    import org.xml.sax.SAXParseException;
    import org.xml.sax.DocumentHandler;
    import org.xml.sax.InputSource;
    import org.xml.sax.helpers.ParserFactory;
    import java.io.*;
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();                   
                   dbf.setNamespaceAware(true);
    DocumentBuilder db = dbf.newDocumentBuilder();                   
    Document xmlDoc =  db.newDocument();
    // this creates the xml document ref
    // parent node reference
    Element rootnd = (Element) xmlDoc.createElement("ALL_TABLES");
    // root node
    xmlDoc.appendChild(rootnd);
    Element rownd = (Element) xmlDoc.createElement("ROW");
    rootnd.appendChild(rownd);
    Element statusnd = (Element) xmlDoc.createElement("FILE_STATUS");
    rownd.appendChild(statusnd);
    statusnd.appendChild(xmlDoc.createTextNode("Y")
    FileOutputStream outpt = new FileOutputStream(outdir + "//forbranch.xml");
    Writer outf = new OutputStreamWriter(outpt, "UTF-8");
    //error is occuring here Since write method is not available in the Document class
    xmlDoc.write(outf);
    outf.flush();

    Hi,
    when I look in the JDK1.4.2 specification I don't see any write method in the Document interface.
    However, your solution is the Transformer class. There you transform your DOM tree into any output you need. Your code sould look something like this:     TransformerFactory tf = TransformerFactory.newInstance();
         // set all necessary features for your transformer -> see OutputKeys
         Transformer t = tf.newTransformer();
         t.transform(new DOMSource(xmlDoc), new StreamResult(file));Then you have your XML file stored in the file system.
    Hope it helps.

  • XML validation using XDK DOM/SAX Parser

    Hello,
    I am trying to validate xml against xsd using SAX/DOM parser, both the files are stored as CLOB column in the database. I have the requirement to report all the validation errors and based on some helpful advice/code from the earlier posts in this forum, I have used the following code to validate and report the errors.
    The code works fine but for large files it never goes beyond a certain number of errors i.e. getNumMessages() (XMLParseException) never returns value greater than 100 and thus limits the output of the validation errors. Any pointers to suggest change in code or an alternative will be extremely helpful.
    Datebase Version : Oracle Database 11g Enterprise Edition Release 11.2.0.2.0 - 64bit Production
    CREATE OR REPLACE AND RESOLVE JAVA SOURCE NAMED as package <package name>;
    import java.net.*;
    import java.io.*;
    import java.util.*;
    import java.sql.SQLException;
    import oracle.sql.CLOB;
    import oracle.xml.parser.schema.*;
    import oracle.xml.parser.v2.*;
    import org.w3c.dom.*;
    public class XMLSchemaVal
    public static String validate(CLOB xmlDoc, CLOB xsdDoc)
    throws Exception
    //Build Schema Object
    XSDBuilder builder = new XSDBuilder();
    Reader xsdInUnicodeFormat = xsdDoc.getCharacterStream();
    XMLSchema schemadoc = (XMLSchema)builder.build(xsdInUnicodeFormat, null);
    //Build XML Object
    Reader xmlInUnicodeFormat = xmlDoc.getCharacterStream();
    // Genereate the SAX
    SAXParser saxparser_doc = new SAXParser();
    // Set Schema Object for Validation
    saxparser_doc.setXMLSchema(schemadoc);
    saxparser_doc.setValidationMode(XMLParser.SCHEMA_VALIDATION);
    saxparser_doc.setPreserveWhitespace (true);
    String returnValue;
    try {
    saxparser_doc.parse (xmlInUnicodeFormat);
    returnValue = "The input XML parsed without errors.\n";
    catch (XMLParseException se) {
    returnValue = "Parser Exception: ";
    for (int i=0 ; i < se.getNumMessages(); i++)
    returnValue += "<LN: " + se.getLineNumber(i) + ">: " + se.getMessage(i);
    //returnValue = "Parser Exception: " + se.getNumMessages();
    catch (Exception e) {
    returnValue = "NonParserException: " + e.getMessage();
    return returnValue;
    Function to call the above utility from PL/SQL
    CREATE OR REPLACE FUNCTION F_XMLSCHEMAVALIDATION (P_XML IN clob ,P_XSD IN clob) RETURN VARCHAR2 IS
    LANGUAGE JAVA NAME XMLSchemaVal.validate(oracle.sql.CLOB,oracle.sql.CLOB) return java.lang.String';
    Thanks.

    I have the same question. I have an external DTD. I wish to parse an xml file using XMLParser.xmlparse. If I first call XMLParser.xmlparseDTD and then call xmlparse with the XML_FLAG_VALIDATE will the xml automatically be validated against the previously parsed DTD? There is no DOCTYPE declaration in the xml file.
    The demo code on OTN for Java is great but has no relation to the code you would use in C++ (no set functions in C++).

  • Updating an XML file inside the Jar executable

    Hello all!
    I would like to ask how can i update an XML file that is packaged inside my jar file?
    For intstance:
    I have a Java Application in NetBeans
    Inside a package i have constructed a custom .xml file.
    I can read from this file using
    .....getClass().getResourceAsStream("/.../file.xml")and after that using XPath for querying and works fine.
    I want to update an entry in my xml file so the jar contains now the newly updated file.
    Thanks everyone who spends his time to read this. Hope someone can help me.

    Even if it were possible, it would be a bad idea. A jar file is something you deploy. It can be really hard to manage ongoing maintenance if the thing you deploy changes after you've deployed it.
    Just create a file, in an appropriate place given the user's OS, to hold data that changes after the jar has been deployed. Your application will still be in a single jar; it's just that the application will happen to create additional content outside the jar.

Maybe you are looking for

  • Generate Absence Quota For Every 5 Years Service

    Hi Expert, First of all, I'm not familiar with PCR as I'm new with time management. Annual leave is generated via RPTQTA00 with no problem. But we have another absence quota (long leave) that is given to the employee every 5 years (22 days of leave).

  • How to set default reject reason in VA01 (create sales order)

    Hi Everybody can tell me how to set default reject reason for item in sales order. in our sap system there are a default reject reason as '90'. We want to set it as "Null". Thanks Henry

  • How to highlight columns in the report

    Hi, I have two tables/views with same structure, one is with old data and one is with new data (there may be one or more changes in the column for a row). My application has to generate a report comparing these two tables/views and display only chang

  • Insignia LCD NS-LCD32 Picture Prb

    I've developed a vertical line in the exact center of the screen with the color on the left side ok but greenish hues on the right side.  The unit is 18 months old.  Is this an adjustment I can do?  How? Thanks Rudy

  • Too much tapping to change tracks?

    Now someone please correct me if im wrong. When you pick a song on the new nano, the album cover comes up? You have to then tap the screen again to bring up the next track icon, and tap that change the track? So if you wanted to move forward 1 track,