DOM Document to string output... HELP

Currently I am building an XML document using DOM and am requierd to output the generated document as text/String. Is there a method in the API to do this or do I need to parse the document and create the string manually? I'm surprised not to have found such a method, as XML is a text format, and displaying a document as text must be a common requirement.
Thanks in advance,
G Powell

Hi,
if you are using the Crimson implementation you have to cast you Document to a org.apache.crimson.tree.XmlDocument which has a write(OutputStream) method. Write the stream to a file.
If you are using Xerces implementation you have to wrap your Document in a org.apache.xml.serialize.OutputFormat object. Then follow these steps:
OutputFormat format = new OutputFormat((Document)doc);
serializer = new XMLSerializer(format);
serializer.reset();
serializer.setOutputByteStream(out);
serializer.serialize(((Document)doc).getDocumentElement());
Again you are using an OutputStream (out) to write to and then use that to write to file. I think there are other ways of doing this but those are the ones I know.
Hope that helps.

Similar Messages

  • How to put org.w3c.dom.Document into String

    Hello!
    I have some sample xml file with xml schema (xsd file). After parsing this sample file into org.w3c.dom.Document I would like to put it into the string and print out for test purpose only. But I don't know how to do it.
    I would like to print something like
    <somebody>
    <first>First somenthing</first>
    <second>Second something</second>
    </somebody>
    Thanks for your advices.

    The function you have specified works fine and gives back the string from DOM object.But it ruins all the formatting associated with the XML (like new line character)
    Is there any way to overcome it?
    Currently if i have a xml as
    <student>
    <firstname>
    </firstname>
    </student>
    The output of the code u have sent strips off the new line characters and returns everything in a single line as below:
    <student> <firstname> </firstname> </student>
    Thanks for any help associated with above problem.

  • Dom Document to String

    Hi!
    I am looking for a method to create a String from a Dom Document. I have been searching on the internet but all the methods I have found so far contain some deprecated classes :( . Can anyone help me please?
    Thanks in advanced

    georgemc wrote:
    When I saw [this cartoon|http://xkcd.com/763/], I instantly thought of some of the dancing about you have to do with JAXP sometimes
    :-)

  • Org.w3c.dom.Document  to  String?

    Hi.
    How do I create a String (or a file) from a org.w3c.dom.Document object?
    thanks in advance
    [jarimba]

    I just randomly picked one of the hundreds of posts asking this same question:
    http://forum.java.sun.com/thread.jsp?forum=34&thread=301336

  • Covert org.jdom.Document to org.w3c.dom.Document

    Hello,
    How would I convert org.jdom.Document to org.w3c.dom.Document??
    I'm creating org.jdom.Document from the servlet that reads from the database, which gets output like following.
    // doc is org.jdom.Document
    Document doc = new Document( root );
    reportName = new Element( "REPORT_NAME" );
    root.addContent( reportName );
    reportName.setText( "Current Account Balance" );
    // skip...
    XMLOutputter outputter = new XMLOutputter(" ", true, "UTF-8");
    outputter.output(doc, out);
    And in my caller servlet, I read from the previous servlet using URL and parse it, trying to get Document, but it
    InputSource xmlSource = new InputSource( url.openStream());
    //Use a DOM Parser (org.apache.xerces.parsers.DOMParser)
    DOMParser parser = new DOMParser();
    parser.parse( xmlSource );
    Document doc = parser.getDocument();
    // and I do transformation.
    DOMSource inXML = new DOMSource( doc );
    StreamResult outXML = new StreamResult( out );
    transformer.transform( inXML, outXML )
    I'd like to skip passing around XML and share the same Document object so that I don't have parse it again...
    Help!

    Convert jdom document to dom document with class DOMOutputter.
    org.jdom.output.DOMOutputter domOut=new DOMOutputter();
    org.w3c.dom.Document domDocument=domOut.output(org.jdom.Document jdomDocument);

  • Transform Document to String

    What is an easy way to transform the contents of a org.w3c.dom.Document to String and vice versa?

    You can use xerces parser for getting the XML string from Document object. There are Classes to provide this functionality. I have pasted the code here. Let me know if you have any problems
    import org.w3c.dom.Document;
    import org.apache.xml.serialize.OutputFormat;
    import org.apache.xml.serialize.XMLSerializer;
    import java.io.StringWriter;
    import java.io.FileReader;
    import java.io.File;
    import java.io.FileReader;
    import org.xml.sax.InputSource;
    import org.apache.xerces.parsers.DOMParser;
    public class XmlString{
         public static void main(String a[]) throws Exception{
              try{
              File file = new File("root.xml");
              FileReader fileReader = new FileReader(file);
              InputSource     inputSource = new InputSource(fileReader);
              DOMParser domParser = new DOMParser();
              domParser.parse(inputSource);
              Document doc = domParser.getDocument();
              OutputFormat format = new OutputFormat(doc, "ISO-8859-1", true);
              format.setStandalone(true);
              format.setIndenting(true);
              StringWriter stringOut = new StringWriter();
              XMLSerializer serial = new XMLSerializer(stringOut, format);
              serial.asDOMSerializer();
              serial.serialize(doc.getDocumentElement());
              System.out.println("XML CONTENT "+stringOut.toString());
              catch(Exception e){
                   System.out.println(" EXP "+e);
    Have a nice day
    regards
    Paulraj C

  • String to org.w3c.dom.Document conversion problem

    Hi all
    I am using JDK 5 and am having scenario to convert String to w3c.Document object , by the way of finding solution i got a code snippet in sun forum
    final String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><DATA>sample</DATA>"; // xml to convert
    final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    final DocumentBuilder builder = factory.newDocumentBuilder();
    final Document document = builder.parse(new InputSource(new StringReader(xml)));
    System.out.println(document);
    But when i try to execute this code , am gettng output as null. , i dont know why this code behaving like that , can you please help me to solve the problem?
    Thanks
    Prabu.P

    imprabu wrote:
    I am using JDK 5 and am having scenario to convert String to w3c.Document object, by the way of finding solution i got a code snippet in sun forum
    System.out.println(document);
    Hi Prabu,
    This is not the way you can print a DOM Document. You can do it using Transformer:
    String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><DATA>sample</DATA>"; // xml to convert
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document document = builder.parse(new InputSource(new StringReader(xml)));
    //Wong Way of printing a DOM Document. this equal to Object.toString(), Which is of no use for you.
    System.out.println(document); // It will just print: [#document: null]
    // Using Transformer to print DOM Document
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    Source source = new DOMSource(document);
    Result output = new StreamResult(System.out);
    transformer.transform(source, output); // This will print: <?xml version="1.0" encoding="UTF-8"?><DATA>sample</DATA>*Cheers,
    typurohit* (Tejas Purohit)

  • Namespace prefix in created DOM document string

    Hello world,
    I am creating a DOM document using the standard JAXP APIs. The document is not parsed from anywhere, just created using the DOM API factory methods. This document is a SOAP message with the SOAP envelope, header and body elements. Now I need to have this document transformed to an XML string.
    I can manage all this. However, I want to have the SOAP namespace set for the SOAP elements, and I want it set using a prefix (such as "SOAP-ENV" or "env" as in the example below). I have set the envelope, header and body element namespaces to the soap namespace. The rest of the elements inside header and body I have set to null namespace. I want them without any prefix (and what namespace will that be then, default?).
    The problem is, when I transform the document to a string, the namespace is set on the envelope without a prefix, and not on the header or body. I guess this is because the child elements will all inherit the namespace? I tried with xalan and saxon.
    Here is an example of output that would look like what I want:
    <env:Envelope xmlns:env="http://www.w3.org/2002/12/soap-envelope">
    <env:Header>
      <foo>hello</foo>
    </env:Header>
    <env:Body>
       <bar>is open</bar>
    </env:Body>
    </env:Envelope>Here is an example of output that looks like what I got:
    <Envelope xmlns="http://www.w3.org/2002/12/soap-envelope">
    <Header>
      <foo>hello</foo>
    </Header>
    <Body>
       <bar>is open</bar>
    </body>
    </Envelope>So so what am I doing wrong, how should I do it? If my rambling makes no sense, even an example of constructing output like the example of what I want would solve this.. :)
    Thanks,

    You could just create the an attribute like this:
    root.setAttribute("xmlns:env", "http://www.w3.org/2002/12/soap-envelope"); where root is the Envelope element.
    Hello world,
    I am creating a DOM document using the standard JAXP
    APIs. The document is not parsed from anywhere, just
    created using the DOM API factory methods. This
    document is a SOAP message with the SOAP envelope,
    header and body elements. Now I need to have this
    document transformed to an XML string.
    I can manage all this. However, I want to have the
    SOAP namespace set for the SOAP elements, and I want
    it set using a prefix (such as "SOAP-ENV" or "env" as
    in the example below). I have set the envelope,
    header and body element namespaces to the soap
    namespace. The rest of the elements inside header and
    body I have set to null namespace. I want them
    without any prefix (and what namespace will that be
    then, default?).
    The problem is, when I transform the document to a
    string, the namespace is set on the envelope without
    a prefix, and not on the header or body. I guess this
    is because the child elements will all inherit the
    namespace? I tried with xalan and saxon.
    Here is an example of output that would look like
    what I want:
    <env:Envelope
    xmlns:env="http://www.w3.org/2002/12/soap-envelope">
    <env:Header>
    <foo>hello</foo>
    </env:Header>
    <env:Body>
    <bar>is open</bar>
    </env:Body>
    </env:Envelope>Here is an example of output that looks like what I
    got:
    <Envelope
    xmlns="http://www.w3.org/2002/12/soap-envelope">
    <Header>
    <foo>hello</foo>
    </Header>
    <Body>
    <bar>is open</bar>
    </body>
    </Envelope>So so what am I doing wrong, how should I do it? If my
    rambling makes no sense, even an example of
    constructing output like the example of what I want
    would solve this.. :)
    Thanks,

  • Org.w3c.dom.Document to/from String ?

    I need to be able to parse (once) an XML string, and then pass the parsed object around to/from different objects.
    I tried to use org.w3c.dom.Document,
    generated by javax.xml.parsers.DocumentBuilder .
    HOWEVER - I don't see any way to parse an xml String!
    The doc-builder parse() method accepts either a file/url, or an InputStream.
    When I tried to use the StringBufferInputStream I found-out it is deprecated, and that I should use StringReader.
    BUT I cannot parse using StringReader ! (the method parse() doesn't work with it)
    Is there anyway to parse a String to create a Document ?
    ========================================================
    And that's only HALF my problem:
    I did parse an input file into a Document, to experiment a little.
    I then wanted to convert it to an XML String - but couldn't.
    How do I get the xml String from a Document ?
    I cannot: How do I save it to a file ?
    I must say that under .NET both tasks are TRIVIAL:
    XmlDocument.LoadXML()
    XmlDocument.OuterXml
    Thanks
    Meir

    The doc-builder parse() method accepts either a file/url, or an InputStream.This isn't true. Look it up again. There are overridden versions of parse() that use File, InputSource, InputStream, or String. The String one isn't what you want, because the String it takes is a URL pointing to the XML and not the XML itself. The File one doesn't work for you because you don't have a file, and you've already said why the InputStream one doesn't work for you.
    So that leaves the version that takes an InputSource. So, what is an InputSource anyway? You could look it up just by clicking on the link in the API docs...

  • How to append an xml string as a child node to a dom document

    Hi
    I have an xml represented as a String. Now I want to add this xml string as a child node to another DOM Document.
    Do I have to first parse the xml String into a xml Document and then add the nodes to the existing Document. Is there a simpler way to do this. Any input is appreciated.
    Many thanks in advance.

    radsat wrote:
    Hi
    I have an xml represented as a String. Now I want to add this xml string as a child node to another DOM Document.
    Do I have to first parse the xml String into a xml Document and then add the nodes to the existing Document. yes, this is what you need to do.
    Is there a simpler way to do this. Any input is appreciated.no, there really isn't, sorry.

  • How can I convert a String to a DOM document?

    I want to convert the text of a TextArea to a DOM Document - how can I do this?
    Thanks a million,
    Daniel.

    something.parse(new StringReader(theTextArea.getText()));

  • How to convert clobDomain to org.w3c.dom.Document

    Hi
    We have store the xml data into oracle database as clobDomain.We are reading the same data from db and want to convert it into org.w3c.dom.Document type.We used the method getXMLContentNode() but its doesn't help us.See the below code.
    ClobDomain pedigreeXML = (ClobDomain) pedigreeDocumentRow.getAttribute("PedigreeDocument");
    DocumentBuilderFactory docBuildFactory= DocumentBuilderFactory.newInstance();
    Document containerDoc = docBuildFactory.newDocumentBuilder().newDocument();
    System.out.println(containerDoc.toString()); // this sop statement printing the xml fine
    Node node= pedigreeXML.getXMLContentNode(containerDoc);
    System.out.println(node); // this sop statement is printing data as "oracle.xml.parser.v2.XMLCDATA@1de6ded"
    Please let me know can we convert clobDomain to Document type.
    Thanks
    Baji

    Baji,
    it would help if you give the jdev version you are working on...
    I don't see a problem with the output you get from System.out.println(node); // this sop statement is printing data as "oracle.xml.parser.v2.XMLCDATA@1de6ded"as it only prints you the address of the node, but not the content. Try
    String str = node.getTextContent();and check if this get you the content.
    Timo

  • XDK 10.1.0.2.0 NT XMLType and org.w3c.dom.Document problem/bug?

    Hi Chaps,
    I have Oracle 11g1 server side and am using the Oracle XDK 10.1.0.2.0 for Windows client side with Sun Java JDK 6 (1.6.0_06-b02).
    (I couldnt find an XDK for 11g1???)
    I have a table in my database that has an XMLType, its a very simple table -
    CREATE TABLE hcr_xml_test
    RRN VARCHAR(24) PRIMARY KEY,
    ClipID VARCHAR2(27),
    Lodgement XMLType
    XMLTYPE COLUMN Lodgement
    STORE AS OBJECT RELATIONAL
    ELEMENT "/www.hcrregister.com/RequestServices/Messages/ConditionReportCreateRequest_1.xsd#ConditionReportCreateRequest_1"
    Thats all fine, however with the XDK I am trying to construct an XMLType for use with JDBC from a valid org.w3c.dom.Document so that I can insert a row into my table. My code looks like this -
    XMLType xml = new XMLType(realCon, doc);
    stmt = (OraclePreparedStatement) realCon.prepareStatement(sql);
    stmt.setString(1, id.getRRN());
    stmt.setString(2, id.getCenteraClipID());
    stmt.setObject(3, xml);
    stmt.execute();
    doc is a org.w3c.dom.Document
    realCon is a java.sql.Connection
    That code throws a SQLException at the line "stmt.setObject(3, xml);" -
    java.sql.SQLException: Fail to convert to internal representation
    at oracle.jdbc.driver.SQLStateMapping.newSQLException(SQLStateMapping.java:70)
    at oracle.jdbc.driver.DatabaseError.newSQLException(DatabaseError.java:112)
    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:173)
    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:229)
    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:403)
    at oracle.sql.OPAQUE.<init>(OPAQUE.java:85)
    at oracle.xdb.XMLType.toDatum(XMLType.java:480)
    at oracle.jdbc.driver.OraclePreparedStatement.setORADataInternal(OraclePreparedStatement.java:7437)
    at oracle.jdbc.driver.OraclePreparedStatement.setObjectInternal(OraclePreparedStatement.java:8158)
    at oracle.jdbc.driver.OraclePreparedStatement.setObject(OraclePreparedStatement.java:8149)
    at oracle.jdbc.driver.OraclePreparedStatementWrapper.setObject(OraclePreparedStatementWrapper.java:229)
    at uk.co.landmarkinfo.registers.datawarehouse.tools.oracle.lodgementloader.DocumentProcessor.run(DocumentProcessor.java:232)
    Inspecting the exception I can see that the vendorCode is 17059.
    If I use "XMLType xml = XMLType.createXML(realCon, doc);" then xml is null instead of throwing a SQLException, so something isnt working here...
    However, if I serialize my Document to a String first and give that String to either the XMLType Constructor or XMLType.createXML() then it all works fine -
    /////TEMP
    Transformer transformer = saxTransformerFactory.newTransformer();
    transformer.setOutputProperty("omit-xml-declaration", "no");
    transformer.setOutputProperty("indent", "yes");
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    transformer.transform(new DOMSource(doc), new StreamResult(baos));
    XMLType stringXML = new XMLType(realCon, new String(baos.toByteArray()));
    ////END TEMP
    stmt = (OraclePreparedStatement) realCon.prepareStatement(sql);
    stmt.setString(1, id.getRRN());
    stmt.setString(2, id.getCenteraClipID());
    stmt.setObject(3, stringXML);
    stmt.execute();
    But why do I need to serialize to a String first??? Looking at the javadoc I dont think I should have to do this. So is there a problem in Oracles XDB handling of Document or have I missed something?

    Anyone has any idea? Please help!!!
    xu

  • Create a DOM Document with DTD

    When creating a new DOM Document, how to specify it's DTD?
    This ...
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setValidating(true);
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document d = db.newDocument();
    Element e = d.createElement("lolcats");
    d.appenChild(e);... outputs ...
    <?xml version="1.0" encoding="UTF-8"?>
    <lolcats/>.. but i want ...
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE lolcats SYSTEM "lolcats.dtd">
    <lolcats/>Plx help
    Edited by: CapM on Feb 7, 2008 11:10 AM

    Update: a workaround for my problem is to set the DTD during serialization:
    OutputFormat of = new OutputFormat(d);
    of.setDoctype(null, "lolcats.dtd");Yet not what i'm looking for.

  • Using a DOM Document in Graphical Mapping

    Hi,
    I have the following scenario:
    A string stream is received from a SOAP adapter. From this   I extract a part that is in essence a XML document.
    I then parse this into a DOM Document object. 
    I want to pass this XML structure on to other graphical mapping functions so that I can map parts of this document to other structures. I cannot add it to the 'result' object in an 'Advanced user defined function'
    Do I have to add it to some component of the 'container' object passed to the function ?.  If not - any ideas of how I would do this ?.
    Thanks
    Andre

    Hi Andre,
    It looks to me like you have an XML document with another XML document embedded (and encoded) inside some element. Something like:
    <outerDoc>
    <element>
      &lt;innerDoc&gt; ...more embedded XML... &lt;/innerDoc&gt;
    </element>
    </outerDoc>
    It is not possible to both "unwrap" the inner document and continue to work on it in a graphical mapping. The simplest approach is to have 2 mapping steps in your interface mapping:
    1. A pure Java mapping in which you get the complete outer document as input, parse your way through and extract the inner document, which is the output of this first mapping step.
    2. A graphical mapping which has your inner document as input and your final result as output.
    Hope that clarifies it somewhat
    Best regards,
    Thorsten

Maybe you are looking for

  • Help with using the pen tool

    I have a few different problems with the pen tool. 1. When using the pen tool I keep finding that the shape I'm doing is slightly overlapping where I've already gone with the pen tool. If I try and go over that area again the path I've just drawn the

  • Data is lost while I'm restoring

    I just installed a new 2TB HD and was in the process of restoring almost 1.5TB of Video from my Time Machine backup. All was going well then I had an error code 47 or 43. Can't remember offhand. So I went to start the process again and I couldn't go

  • Vendor confirmation best practice or whitepaper

    Do anyone have a best practice document or whitepaper from SAP or customer? I would be appreciated. Thanks.

  • Dynamic function Call

    Hi, I want to search which program is using the FM : FKK_AR_EVENT_0934. I tried using Where used List but it says "Possible Dynamic Calls'. How to search for that? Thanks, Sachin.

  • Documents to Go on Palm TX Syncing with Vista

    I cant seem to get my documents to sync with my Palm TX. Everytime I click on the Documents To Go icon on my Vista desktop it gives me a "Runtime error" message. Help! What do I do? Post relates to: Palm TX