[Q] convert DOM to XML Document

Hi,
Is there any class or library which convert DOM to XML document?
----- java program ------------
import org.w3c.dom.*;
import org.apache.crimson.tree.XmlDocument;
public class Sample {
  public static void main(String args[]) {
    // create a document and root element
    Document doc = new XmlDocument();
    Element root = doc.createElement("html");
    doc.appendChild(root);
    // append a data
    Element body = doc.createElement("body");
    root.appendChild(body);
    body.appendChild(doc.createTextNode("Hello"));
    // convert DOM to XML Document
}----- expected result ----------
<html>
<body>
  Hello
</body>
</html>Could you help me?

Hi,
Look at the package javax.xml.transform
or
try the following code:
I tried the following code.
----- java program ------------
import javax.xml.parsers.*;
import org.w3c.dom.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import java.io.OutputStream;
public class Sample {
  public static void main(String[] args) {
    try {
      // create a document and root element
      Document doc = DocumentBuilderFactory.newInstance()
                            .newDocumentBuilder()
                            .newDocument();
      Element root = doc.createElement("html");
      doc.appendChild(root);
      // append a data
      Element body = doc.createElement("body");
      root.appendChild(body);
      body.appendChild(doc.createTextNode("Hello"));
      Element ul = doc.createElement("ul");
      String[] list = {"foo", "bar", "baz"};
      for (int i=0; i<list.length; i++) {
       Element li = doc.createElement("li");
       li.appendChild(doc.createTextNode(list));
     ul.appendChild(li);
body.appendChild(ul);
// convert DOM to XML Document
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
//OutputStream stream = new FileOutputStream("output.xml");
OutputStream stream = System.out;
transformer.transform(new DOMSource(doc), new StreamResult(stream));
} catch (Exception ex) {
     ex.printStackTrace();
----- result ------------
<html>
<body>Hello<ul>
<li>foo</li>
<li>bar</li>
<li>baz</li>
</ul>
</body>
</html>Great! Very thanks!

Similar Messages

  • Converting string to xml Document object.

    Hi all,
    I having a string consiste of xml data.
    I wants to convert this to an xml document object.
    When i am trying to do this i am getting fatal error Premature End of file.
    This is sample code from my program.
    String xmlStr = " <TravelItineraryAddInfoRQ>
    <POS>
    <Source PseudoCityCode="A2PB"/>
    </POS>
    </TravelItineraryAddInfoRQ>";
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware( false );
              DocumentBuilder builder = null;
              char[] ch = new char[1200];
    builder = factory.newDocumentBuilder();
    StringReader sr = new StringReader(xmlStr);
    InputSource is = new InputSource(sr);
    Reader r = is.getCharacterStream();
    r.read(ch);
    System.out.println("String Starting ==== ");
    for(int i=0;i<ch.length;i++)
    System.out.print(ch);
    Document XMLDoc = builder.parse(new InputSource(sr));
    System.out.println("Document Object ==== "+XMLDoc);
    thnx,
    raj

    Hi Rajaven,
    use the below step, I think it could help u
    StringBufferInputStream sb = new StringBufferInputStream(strBf));
    doc = db.parse(sb);first conver a string to StringBufferInputStream then parse to doc Object
    hope it will solve.
    let me know if it's not working
    With cheers,
    PrasannA

  • Convert report to xml document

    hi,
    how can i create or generate xml document of my report?
    or how can i generate xml document for whole data of table....?
    thanks
    regards shailesh..

    If all the checks were o.k.
    it may help to split the transformation
    (I don't know why, so please ask someone from SAP why this makes a difference)
    Replace
    CALL TRANSFORMATION (`ZXSLT_XML_ABAP`)
    SOURCE xml = pIStream
    RESULT EMP_INFO = EMP_ITAB.
    by
    data: lv_string TYPE string.
    CALL TRANSFORMATION (`ZXSLT_XML_ABAP`)
    SOURCE xml = pIStream
    RESULT XML lv_string.
    CALL TRANSFORMATION id
    SOURCE XML lv_string
    RESULT EMP_INFO = EMP_ITAB.

  • Converting jtree to xml

    hi, i am currently working on a project where i construct a jtree using a java gui....once the user clicks on save button, the jtree has to be read and converted into an xml document....
    for eg, the jtree looks like this
    - process
    ----reply
    ----receive
    etc..
    the xml document should be as follows:
    <process>
    <reply> </reply>
    <receive></receive>
    </process>
    i need your help in this regard....kindly help
    Regards
    Lalitha

    Chapter 23 of the book, constructs a tree XMl editor, and it saves among other things...
    http://www.manning.com/sbe/

  • Can anyone help me in converting a dom to xml

    hi,
    i am facing a problem in using transformer factory to convert a dom to xml.
    please help me.
    if anyone has a sample code in java please share with me.

        static public void serialize( Document doc, File outFile)
            try
               TransformerFactory tfFac = TransformerFactory.newInstance();
               Transformer tf = tfFac.newTransformer();
               // tf.setOutputProperty("indent", "yes");
               tf.transform(new DOMSource(doc),
                  new StreamResult(new FileWriter( outFile )
            }         // end of try
            catch( FileNotFoundException fnfe )
               System.err.println( "File Creation Error in serializer" );
               System.err.println( fnfe.getMessage() );
            }         // end of catch
            catch (TransformerException e)
                e.printStackTrace();
            }         // end of catch
            catch( IOException ioe )
               System.err.println( "IOException in serializer" );
               System.err.println( ioe.getMessage() );
            }         // end of catch
        }Dave Patterson

  • Can't get the DOM to output XML document tags in correct order.

    I'm trying to output an XML document from the DOM using the DOMWriter class: new DOMWriter(document, filename, outputEncoding, encodingTag, getDocTypeString());
    It refuses to output the tags in the correct order so my document always fails validation when it is read back in. I've tried explicitly placing the elements in the correct order into the DOM and it still outputs them the way it wants to. Is there some method I'm missing to set the xsd or dtd to validate the output on. It actually appears as though it has a definite idea as to what order the tags should be output, because no matter what order I append the nodes into the document, it always outputs them in the same incorrect order. I've got the validation working when it reads the document in. Does anyone know what I have to do to get it to output the tags in the correct order?

    Does anyone know what I
    have to do to get it to output the tags in the correct
    order?You have to build the DOM in the correct way. Based on the code you posted it's impossible to tell what you are doing wrong. How about posting some code?

  • Fm 12 - How can I include a graphic in an XML document that will be zoomable when converted to HTML5?

    I'd like to inc;lude grahics in my help files when authoring them in xml and converting them to Responsive HTML5 web documents.  I'm not sure of the proper way to inc;lude javascript scripts into the XML documents that could be used to make the images zoomable and panable.  Codeblock elements don't seem to work - all that happens is the text of the script is displayed in a font different from the font I'm using for the Help text. Maybe I'm using the wrong elements?  I'm using Framemaker 12. Any ideas here would be greatly appreciated.

    Anyone? Im also frustrated about this

  • Inserting XML document into XDB fails with can't convert to OPAQUE

    Hi,
    When I try to insert a document using oracle 9.2.0.5 client software into a 9.2.0.5 database, with the following code:
    void insertDocument(String document) {
    XMLType xt = XMLType.createXML(connection, document);
    PreparedStatement ps = connection.prepareStatement("insert into xmldocuments values(?)");
    ps.setObject(1, xt);
    ps.executeUpdate();
    The setObject function always throws an exception (after a very long time) with:
    java.sql.SQLException: Fail to convert to internal representation: OPAQUE()
    This also fails when we use the InputStream and org.w3c.xml.Document variants.
    We use the OCI driver, otherwise we get errors retrieving the documents from XMLDB.
    What is going wrong here?

    David,
    If you search through the historical data in this list there are previous post regarding opaque.
    These may be useful. Possibly your reaching the size limit.

  • Converting XML document to HTMl using xsl

    Hi,
    I'm trying to convert an xml document into html page using xsl. But when I try to open the page in the browser nothing comes up.
    I'm not sure if I am using the PrintWriter correctly.
    StreamResult result = new StreamResult(new PrintWriter(new (File"text.html")));
    Please help.

    Oops! I wrote the parenthesis wrong in the previous mail
    This is the correct one I use in my program.
    StreamResult result = new StreamResult(new PrintWriter(new File("text.html")));
    Please help. Its urgent

  • Converting XML Document to String

    Dear All,
    I am quite new to Java Web Services. I have made a Java Class which calls all the web services . I am displaying the results on a Command prompt. Below is my sample code:
    import javax.xml.rpc.Service;
    import javax.xml.rpc.Stub;
    import horusWS.Horus_x0020_Web_x0020_Services_Impl;
    import horusWS.Horus_x0020_Web_x0020_ServicesSoap;
    public class JavaClient {
    public static void main(String[] args)
    Horus_x0020_Web_x0020_Services_Impl service = new Horus_x0020_Web_x0020_Services_Impl();
    Horus_x0020_Web_x0020_ServicesSoap port = service.getHorus_x0020_Web_x0020_ServicesSoap();
    String str;
    str = port.getTextFeedbackLearner(1,"P001",1);
    //where getTextFeedbackLearner is the my Web Service.
    System.out.println(str);
    System.out.println returns the web service in string format. Now I want to compare this string to my actual getTextFeedbackLearner.xml file. But I think I need to convert getTextFeedbackLearner.xml to string first. Please let me know
    how can I convert an XML Document to String.
    Thanking you in Anticipation.
    cheers,
    Sunil Sabir

    You can read the XML document as you read any other file.
    Read it into a String variable.
    Check java.io.FileReader, java.io.BufferReader, etc.

  • Xml document converting to pdf

    Hi,
    I have a question regarding the convertion of xml document to pdf document.
    Below is the scenario.
    I have an xml document stored in the table in a CLOB format. I would like to convert the xml document stored in a table to pdf document and display in a Web browser.
    I have written the stylesheet to convert the xml document to the xsl fo(XSL Formatting object xml) type document. I need to apply FOP Processor to convert into pdf document.
    How do i do that in PL/ SQL ?
    Any thoughts ??

    1. Generate a XSL-FO document by applying an XSLT to the XML document in the database.
    2. Convert the XSL-FO document to a PDF document.

  • Filling tab of an XML document created by DOM

    have a problem with filling tab of an XML file created by DOM
    I used this code to create the document:
    public class DOMCreation {
    public void createDOM( String a, String b ) {
              Document doc = new DocumentImpl( null );
              // Il codice che segue � indipendente dal particolare parser utilizzato
              // Creazione dell'elemento root del documento, identificato dal tag <DOCUMENT>
              Element root = doc.createElement("DOCUMENT");
              doc.appendChild(root);
              // Creazione ed inserimento di un nodo
              Element element1 = doc.createElement("USERNAME");
              root.appendChild( element1 );
              // Creazione ed inserimento di un secondo nodo discendente di <DOCUMENT>
              root.appendChild( doc.createElement("PIN") );
    System.out.println( a );
    System.out.println( b );
              try {
                   serializeDocument( doc, new FileOutputStream("d:/doc.xml"));
              } catch (FileNotFoundException e) {}
    private static void serializeDocument(Document doc, OutputStream output) {
              try {
                   DOMSerializer ser = new XMLSerializer( output, null);
                   ser.serialize(doc);
              } catch (IOException e) {
                   System.err.println("I/O exception while serializing document: " + e.getMessage());
    }

    The code lines:
    System.out.println( a );
    System.out.println( b );
    had the purpose to check if these two parameters were passed by another procedure. These two parameters, however, represent the content to be filled in the tag of XML document created by DOM.
    About the other question on "what parser do you use", I'm using Apache's Xerces. However that's the "import" that I include in this procedure:
    import org.apache.xerces.dom.DocumentImpl;
    import org.apache.xerces.dom.NodeIteratorImpl;
    import org.apache.xml.serialize.*;
    import org.w3c.dom.*;
    import org.w3c.dom.traversal.*;
    import java.io.*;

  • How can I use DOM to copy Nodes between different XML Document ?

    Can I copy one Node or Element from one XML Document to another Document by DOM ?
    Because I use the Xerces , but it is not work if I want to copy Node between different Document, or I am doing something wrong. Anyone can help me , I will deeply appreciated !!

    check out the importNode() method of Document.

  • Convert  Objects into an XML Document? Possible?

    Hello,
    Is there a way to convert different objects into an XML File/Document
    If I create 10 objects and then I want to create an XML Document
    of these objects,is it possible to do this?
    Ajay

    Hello,
    Is there a way to convert different objects into an
    XML File/Document
    If I create 10 objects and then I want to create an
    XML Document
    of these objects,is it possible to do this?
    Ajayjust override the .toString() method...

  • Loading XML document for DOM parsing

    Can anyone suggest other API's to load a XML document into memory so they can be parsed using the DOM with Java?(e.g. The "load(url)" interface method specific to IE5)
    Thanks

    Check out the DOMSample.java code came with the XML Parser for Java v2 download.
    Oracle XML Team

Maybe you are looking for

  • Function module to pass senders email id.

    I need a FM wherein the senders as well as recievers email should be passed.The objective being that we have jobs on auto scheduler.The SO_NEW_DOCUMENT_SEND_API1 FM pickups the userid of execution job which has been scheduled to run.I would like the

  • My Canon MP620 just stopped printing text: it can print photos etc but when I send a word document (with a picture) it only prints the picture. Any ideas?

    Hi Everyone: I have a  Canon MP620 printer connected directly into my Airport base station. So far it has worked perfectly - I can print any type of document over the network from my MacBook Pro. Yesterday something weird happened. I have a resumé (a

  • Scale in Charts

    Hi, I want to set the scale of X axis based min value of the fact.... Lets say i have an analysis where fact measure values are all in between 85 and 100. So for better visibility i wanted the scale to start from the same. This should be dynamic as g

  • Drag & Drop & Copy and Paste

    Before intalling Leopard I was able to drag jpegs out of safari and onto my desktop or find album artwork and drag it into itunes this feature seems to no longer work. Is there a setting somewhere I can change? Also can no longer copy a URL and paste

  • Error Msg 110 and 275

    Everytime my phone reboots, or turns off, so when i download something or erase something and it needs to reboot, I get "uncaught exception: Application net_rim_bb_messaging_app(275) is not responding; process terminated. And Application net_rim_bb_m