Generation of Xml file with java output

Hi i m new to xml and java combination. I have a name value pair kind of output returning from java program. I want to generate the new xml file with the data. Could some one help me out in generating xml file with the data. Could anyone send me the java code that does this task.

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

Similar Messages

  • Generation of xml file from java code

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

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

  • How to validate the Xml File With Java

    Hi,
    Can pls tell me. I want to validate the XML File for the Some Mandartory TAG. if that if Tag null i want to generate error xml file with error and i want move another folder with java. pls help me as soon as possible

    Use a validating parser (any recent Xerces, for one) and switch on the validation feature. Very much vendor-specific, so look at the docs of your parser. Oh, you do have a schema for these documents, don't you?

  • Generation of XML file from Java objects using castor

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

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

  • Split XML in Multiple XML files with Java Code

    Hi guys , i have following xml file as input ....
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <T0020
    xsi:schemaLocation="http://www.safersys.org/namespaces/T0020V1 T0020V1.xsd"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.safersys.org/namespaces/T0020V1">
    <INTERFACE>
    <NAME>SAFER</NAME>
    <VERSION>04.02</VERSION>
    </INTERFACE>
    <TRANSACTION>
    <VERSION>01.00</VERSION>
    <OPERATION>REPLACE</OPERATION>
    <DATE_TIME>2009-09-01T00:00:00</DATE_TIME>
    <TZ>CT</TZ>
    </TRANSACTION>
    <IRP_ACCOUNT>
    <IRP_CARRIER_ID_NUMBER>274845</IRP_CARRIER_ID_NUMBER>
    <IRP_BASE_COUNTRY>US</IRP_BASE_COUNTRY>
    <IRP_BASE_STATE>AR</IRP_BASE_STATE>
    <IRP_ACCOUNT_NUMBER>55002</IRP_ACCOUNT_NUMBER>
    <IRP_ACCOUNT_TYPE>I</IRP_ACCOUNT_TYPE>
    <IRP_STATUS_CODE>100</IRP_STATUS_CODE>
    <IRP_STATUS_DATE>2007-11-06</IRP_STATUS_DATE>
    <IRP_UPDATE_DATE>2009-08-03</IRP_UPDATE_DATE>
    <IRP_NAME>
    <NAME_TYPE>LG</NAME_TYPE>
    <NAME>A P SUPPLY CO</NAME>
    <IRP_ADDRESS>
    <ADDRESS_TYPE>PH</ADDRESS_TYPE>
    <STREET_LINE_1>1400 N OATS</STREET_LINE_1>
    <STREET_LINE_2/>
    <CITY>TEXARKANA</CITY>
    <STATE>AR</STATE>
    <ZIP_CODE>71854</ZIP_CODE>
    <COUNTY>MILLER</COUNTY>
    <COLONIA/>
    <COUNTRY>US</COUNTRY>
    </IRP_ADDRESS>
    <IRP_ADDRESS>
    <ADDRESS_TYPE>MA</ADDRESS_TYPE>
    <STREET_LINE_1>P O BOX 1927</STREET_LINE_1>
    <STREET_LINE_2/>
    <CITY>TEXARKANA</CITY>
    <STATE>AR</STATE>
    <ZIP_CODE>75504</ZIP_CODE>
    <COUNTY/>
    <COLONIA/>
    <COUNTRY>US</COUNTRY>
    </IRP_ADDRESS>
    </IRP_NAME>
    </IRP_ACCOUNT>
    <IRP_ACCOUNT> ..... </IRP_ACCOUNT>
    <IRP_ACCOUNT> ..... </IRP_ACCOUNT>
    <IRP_ACCOUNT> ..... </IRP_ACCOUNT>
    </T0020>
    and i want to take this xml file and split it into multiple files through java code like this ...
    File1.xml
    <T0020>
    <IRP_ACCOUNT> ..... </IRP_ACCOUNT>
    <IRP_ACCOUNT> ..... </IRP_ACCOUNT>
    </T0020>
    File2.xml
    <T0020>
    <IRP_ACCOUNT> ..... </IRP_ACCOUNT>
    <IRP_ACCOUNT> ..... </IRP_ACCOUNT>
    </T0020>
    like wise...
    Each xml file contain maximum 10 or 15 IRP_ACCOUNT.
    Can somebody please help me ? How can i do it with stax like start element and all ?
    thanks in advance.

    Ah, sorry, strike that. You want multiple files. I think the easiest way is to simply parse with DOM. [http://www.w3schools.com/xpath/default.asp] . And here [http://www.w3schools.com/xpath/default.asp].
    You can output the various XML elements using a PrintWriter or creating a separate DOM document for each file you want to create and serializing that.
    - Saish

  • Convert an excel (*.xls) file to a xml file with Java Beans

    Hi to all............
    I am new to this ,
    I have a requirement that
    i want to read excel (*.xls ) file which is having some data going to be persist in database. Before going to persist process i want to read that data from xls file and convert those data into xml file.
    Can any one help me how can i do this using java classes?
    Please guide me what are the necessary libraries and requirements to do this?
    If any one have an idea then help me with some example code
    Thanks in advance for your great replay
    Sathish A

    this is the full stack trace i am getting jboss server console
    09:57:17,922 ERROR [application] org.w3c.dom.DOMException: INVALID_CHARACTER_ERR: An invalid or illegal XML character is specified.
    javax.faces.el.EvaluationException: org.w3c.dom.DOMException: INVALID_CHARACTER_ERR: An invalid or illegal XML character is specified.
         at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:102)
         at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
         at javax.faces.component.UICommand.broadcast(UICommand.java:387)
         at org.ajax4jsf.component.AjaxViewRoot.processEvents(AjaxViewRoot.java:324)
         at org.ajax4jsf.component.AjaxViewRoot.broadcastEvents(AjaxViewRoot.java:299)
         at org.ajax4jsf.component.AjaxViewRoot.processPhase(AjaxViewRoot.java:256)
         at org.ajax4jsf.component.AjaxViewRoot.processApplication(AjaxViewRoot.java:469)
         at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:82)
         at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:100)
         at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
         at javax.faces.webapp.FacesServlet.service(FacesServlet.java:265)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
         at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:83)
         at org.jboss.seam.web.IdentityFilter.doFilter(IdentityFilter.java:40)
         at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69)
         at org.jboss.seam.web.MultipartFilter.doFilter(MultipartFilter.java:86)
         at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69)
         at org.jboss.seam.web.ExceptionFilter.doFilter(ExceptionFilter.java:64)
         at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69)
         at org.jboss.seam.web.RedirectFilter.doFilter(RedirectFilter.java:45)
         at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69)
         at org.ajax4jsf.webapp.BaseXMLFilter.doXmlFilter(BaseXMLFilter.java:178)
         at org.ajax4jsf.webapp.BaseFilter.handleRequest(BaseFilter.java:290)
         at org.ajax4jsf.webapp.BaseFilter.processUploadsAndHandleRequest(BaseFilter.java:388)
         at org.ajax4jsf.webapp.BaseFilter.doFilter(BaseFilter.java:515)
         at org.jboss.seam.web.Ajax4jsfFilter.doFilter(Ajax4jsfFilter.java:56)
         at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69)
         at org.jboss.seam.web.LoggingFilter.doFilter(LoggingFilter.java:58)
         at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69)
         at org.jboss.seam.web.HotDeployFilter.doFilter(HotDeployFilter.java:53)
         at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69)
         at org.jboss.seam.servlet.SeamFilter.doFilter(SeamFilter.java:158)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
         at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
         at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230)
         at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
         at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:182)
         at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:432)
         at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:84)
         at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
         at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
         at org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:157)
         at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
         at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:262)
         at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
         at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
         at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:446)
         at java.lang.Thread.run(Thread.java:636)
    Caused by: org.w3c.dom.DOMException: INVALID_CHARACTER_ERR: An invalid or illegal XML character is specified.
         at org.apache.xerces.dom.CoreDocumentImpl.createElement(Unknown Source)
         at org.domain.DigesterDemo.session.ViewList.generateXML(ViewList.java:275)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
         at java.lang.reflect.Method.invoke(Method.java:616)
         at org.jboss.seam.util.Reflections.invoke(Reflections.java:22)
         at org.jboss.seam.intercept.RootInvocationContext.proceed(RootInvocationContext.java:31)
         at org.jboss.seam.intercept.SeamInvocationContext.proceed(SeamInvocationContext.java:56)
         at org.jboss.seam.transaction.RollbackInterceptor.aroundInvoke(RollbackInterceptor.java:28)
         at org.jboss.seam.intercept.SeamInvocationContext.proceed(SeamInvocationContext.java:68)
         at org.jboss.seam.core.BijectionInterceptor.aroundInvoke(BijectionInterceptor.java:77)
         at org.jboss.seam.intercept.SeamInvocationContext.proceed(SeamInvocationContext.java:68)
         at org.jboss.seam.core.MethodContextInterceptor.aroundInvoke(MethodContextInterceptor.java:44)
         at org.jboss.seam.intercept.SeamInvocationContext.proceed(SeamInvocationContext.java:68)
         at org.jboss.seam.async.AsynchronousInterceptor.aroundInvoke(AsynchronousInterceptor.java:52)
         at org.jboss.seam.intercept.SeamInvocationContext.proceed(SeamInvocationContext.java:68)
         at org.jboss.seam.intercept.RootInterceptor.invoke(RootInterceptor.java:107)
         at org.jboss.seam.intercept.JavaBeanInterceptor.interceptInvocation(JavaBeanInterceptor.java:185)
         at org.jboss.seam.intercept.JavaBeanInterceptor.invoke(JavaBeanInterceptor.java:103)
         at org.domain.DigesterDemo.session.ViewList_$$_javassist_2.generateXML(ViewList_$$_javassist_2.java)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
         at java.lang.reflect.Method.invoke(Method.java:616)
         at org.jboss.el.util.ReflectionUtil.invokeMethod(ReflectionUtil.java:329)
         at org.jboss.el.util.ReflectionUtil.invokeMethod(ReflectionUtil.java:342)
         at org.jboss.el.parser.AstPropertySuffix.invoke(AstPropertySuffix.java:58)
         at org.jboss.el.parser.AstValue.invoke(AstValue.java:96)
         at org.jboss.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:276)
         at com.sun.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:68)
         at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
         ... 51 more
    Thanks for your replay

  • How to read and parse a remote XML file with Java

    Hi.
    Using J2SE v1.4.2, I'd like to read and parse a remote file:
    http://foo.com/file.xml
    Is it possible with Java? I'd be extremely grateful if someone could provide me any webpage showing a very simple code.
    Thank you very much.

    How about the following?
         import java.io.InputStream;
         import java.net.URL;
         import javax.xml.parsers.DocumentBuilder;
         import javax.xml.parsers.DocumentBuilderFactory;
         import org.w3c.dom.Document;
         public static void main(String[] args) throws Exception {
              DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
              DocumentBuilder db = dbf.newDocumentBuilder();
              URL url = new URL("http://foo.com/file.xml");
              InputStream inputStream = url.openStream();
              Document document = db.parse(inputStream);
              inputStream.close();
         }-Blaise

  • Read an XML file with java: Document to Node conversion

    Hello,
    I want to read an XML file and convert data into a Node instance because I need this for an XForm application.
    My code is:
    private Node workstationType;
    public Node initModel() {
    try {
    //This one will hold the results
    Document document;
    //loading from XML File
    String fileName="C:\\documents\\iniForm.xml";
    FileInputStream inXML = new FileInputStream(fileName);
    BufferedReader in = new BufferedReader(new InputStreamReader(inXML));
    document = XMLLoader.loadFromStream(in);
    } catch (Exception e) {
    System.err.println("ERROR:" + e.getMessage());
    e.printStackTrace(System.err);
    //Create the node for the root, 'typeOfWorkstation'
    workstationType = document.getDocumentElement(); //A
    //Return the root node
    return (workstationType);
    The problem: I can convert Node instance to Document instance (line A)
    The error message is: "document cannot be resolved".
    How can I do that??
    Thank you
    Sylvain

    Here is my XMLLoader class:
    public class XMLLoader {
         public static Document loadFromStream(Reader reader) throws Exception {
              //Build a DOM document with the reader
              //prepare DOM document
              DOMImplementation impl;
              DocumentBuilder builder;
              try {
                   // Find the implementation
                   DocumentBuilderFactory factory =
                        DocumentBuilderFactory.newInstance();
                   factory.setNamespaceAware(false);
                   factory.setValidating(false);
                   builder = factory.newDocumentBuilder();
                   impl = builder.getDOMImplementation();
                   //Read and parse the XML input stream into a DOM document
                   Document document = builder.parse(new InputSource(reader));
                   return document;
              } catch (IOException ex) {
                   throw new RuntimeException(
                        "[XMLLoader.loadFromFile]: Failed loading the InputStream. Root cause: \n"
                             + ex);
              } catch (Exception ex) {
                   throw new RuntimeException(
                        "[XMLLoader.loadFromFile]: Failed to initialize DOM factory. Root cause: \n"
                             + ex);

  • XML-file with prefix in Java importing

    Hello,
    I have one XML-file with prefix "wf" like this:
       <wf:data>
               <wf:name>NAME</wf:name>
               <wf:description/>
               <wf:creation_time>0001-01-01T00:00:00</wf:creation_time>
               <wf:user wf:ref=""/>
               <wf:properties/>
       </wf:data>the Java-Code like this:
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
              factory.setNamespaceAware(false);
              XPath xpath = XPathFactory.newInstance().newXPath();
              String expression = "./data/name/text()";
              InputSource inputSource = new InputSource("workflow.xml");
                    String result = xpath.evaluate(expression, inputSource);the Java-Code works well, if the prefix does not exist, otherwise I could not get any result. Could somebody please help me?
    Thank you
    Sunny

    I have defined the namespaceI didn't see that in your original post.
    I notice that your XPath expression doesn't include the namespace prefixes and you don't tell it how to map the prefixes to the namespace URIs. I am not sure whether calling factory.setNamespaceAware(false) makes it unnecessary to do that. I wouldn't count on it.

  • Transfer 100M XML file with XSL

    Hi,
    I am trying to transfer 100M XML file with XSL. Input.xml is the XML file, format.xsl is the XSL file. I type in the command line as:
    java org.apache.xalan.xslt.Process -IN input.xml -XSL format.xsl -OUT output.xml
    It got "out of memeory" error. My questions are:
    1. Is it possible to transfer such large XML file with XSLT?
    2. The XSL processor used SAX or DOM to parse XML file?
    3. Any suggestions?
    Thanks.
    James

    maybe?
    java -Xmx200m org.apache.xalan.xslt.Process -IN input.xml -XSL format.xsl -OUT output.xml
    http://java.sun.com/j2se/1.3/docs/tooldocs/win32/java-classic.html

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

  • How do you display xml file with xlst sheet in jsp

    I have an xml file with accompanying xslt file (and several images that are used in a single directory. If I doubleclick on the xml file, it displays perfectly in my browser - Formatting, images and all!
              The 100 dollar question - How do I duplicate this behavior in a JSP page in WebLogic 8.1 using the code in the xml and the accompanying xslt (formatting) file? I tried simple embedding the xml code in the jsp, but that didn't seem to work. What is the secret?
              Okay, I need to add a bit more information here. I understand that it is really easy to just redirect to the XML file. The issue is really security. I want the XML to be inside a jsp that will only allow validated users to view it.
              Another way to look at the problem would be, can I add a jsp security tag to the xml file? Or how to I add the xml code inside a jsp and keep the path references to the xslt and graphics.
              Hope the added information helps
              Thanks,
              Ken
              Message was edited by: KLee - 20050609 10:25 MST
              [email protected]

    This proved out to be the answer. Thanks for the direction!
              import java.io.File;
              import java.io.IOException;
              import java.io.InputStream;
              import java.io.OutputStream;
              import java.io.FileNotFoundException;
              import java.io.FileOutputStream;
              import javax.servlet.ServletException;
              import javax.servlet.http.HttpServlet;
              import javax.servlet.http.HttpServletRequest;
              import javax.servlet.http.HttpServletResponse;
              import javax.xml.transform.Transformer;
              import javax.xml.transform.TransformerConfigurationException;
              import javax.xml.transform.TransformerException;
              import javax.xml.transform.TransformerFactory;
              import javax.xml.transform.stream.StreamResult;
              import javax.xml.transform.stream.StreamSource;
              public class XML_XSLT_Servlet extends HttpServlet {
              protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
                        String xmlfile = req.getParameter("xmlfile"); if (xmlfile==null) xmlfile = "test.xml";
                        String xsltfile = req.getParameter("xsltfile"); if (xsltfile==null) xsltfile = "test.xslt";
                        /* Test if file exists!, or use default file */
                        File f1 = new File(getServletContext().getRealPath("WEB-INF/displayfiles/"), xmlfile);
                        File f2 = new File(getServletContext().getRealPath("WEB-INF/displayfiles/"), xsltfile);
                   if (f1.exists() && f2.exists()) {
                             // System.out.println("Files Found");
                        } else {
                             System.out.println("XML and XSLT Files NOT Found");
                             System.out.println(f1.getPath());
                             System.out.println(f1.getName());
                             xmlfile = "test.xml";
                             xsltfile = "test.xslt";
              InputStream fileXML = getServletContext().getResourceAsStream("WEB-INF/displayfiles/" + xmlfile);
              InputStream fileXSLT = getServletContext().getResourceAsStream("WEB-INF/displayfiles/" + xsltfile);
              OutputStream os = res.getOutputStream();
              TransformerFactory xFactory = TransformerFactory.newInstance();
              StreamSource stylesheet = new StreamSource(fileXSLT);
              Transformer xformer = null;
              try {
              xformer = xFactory.newTransformer(stylesheet);
              } catch (TransformerConfigurationException tfce) {
              tfce.printStackTrace();
              StreamSource input = new StreamSource(fileXML);
              StreamResult output = null;
              try {
              output = new StreamResult(os);
              } catch (Exception e) {
              e.printStackTrace();
              try {
              xformer.transform(input, output);
              } catch (TransformerException xfe) {
              xfe.printStackTrace();
              <pre></pre><pre></pre>

  • Convert XML file to Jave  -- URGENT

    Hi All,
    I am new to java xml.
    I got requirment like that.. source file is xml.. I need to read xml thru java and if any 0(Zeros) are found in any nodes of xml, then I need to comment thta particular node and store the output in new xml file with inserted comments.
    Please any one help me in this regard..
    How can I start ..?
    Thanks
    HTH

    HTH,
    Use Dom for Java API. i.e dom4j.jar which is readily available on http://docjar.com site.
    Using that JAR you can able to give a comment for your XML file.
    regards
    Rajesh

  • How to read the data from Excel file and Store in XML file using java

    Hi All,
    I got a problem with Excel file.
    My problem is how to read the data from Excel file and Store in XML file using java excel api.
    For getting the data from Excel file what are all the steps i need to follow to get the correct result.
    Any body can send me the code (with java code ,Excel sheet) to this mail id : [email protected]
    Thanks & Regards,
    Sreenu,
    [email protected],
    india,

    If you want someone to do your work, please have the courtesy to provide payment.
    http://www.rentacoder.com

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

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

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

Maybe you are looking for