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
:-)

Similar Messages

  • 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

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

  • 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

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

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

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

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

  • 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()));

  • Conversion from document to string

    I want to perform conversion from document to string for tht purpose i m doing sax parser but in the end i m getting null.The same thing if i do with DOM parser its working fine but some problem with sax parser.
    I am attaching the code if anyone can find the problem it would be gr8.
    Thanks in advance.
    public String DocumentToString(Document doc) {
              StreamResult result = null;
              try {
              SAXParserFactory SAXpf = SAXParserFactory.newInstance();     
    SAXParser SAXparser = SAXpf.newSAXParser();
              XMLr = SAXparser.getXMLReader();
         Source sXML = new SAXSource((InputSource) doc);
    result = new StreamResult(new StringWriter());
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.transform(sXML, result);
    catch (TransformerConfigurationException e) {
    e.printStackTrace();
    catch (TransformerException e) {
    e.printStackTrace();
    catch(Exception e)
         System.out.println(e);
    return result.getWriter().toString();
    }

    Paddy,
    There are a couple of ways to create a Word file.  One is to use the Report Generation Toolkit which includes vi's to create and edit Word documents.  Since you are associated with a university you may already have the toolkit.  The other way is to use ActiveX.  You should be able to find examples of both in the forums.  There may also be an example that shipped with LV. 
    Here is one example to get you going http://zone.ni.com/devzone/cda/epd/p/id/992

  • 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

  • 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

  • Document to String

    Hello all,
    I need in my program create very simple xml-like document (1 node without any attributes, few childs without attributes only string values). The easiest way is String concatination, but I want more flexible sollution. So, I desided to use xml packages that are in standart 1.4 jdk, without using any libraries. I'm using now org.w3c.dom.Document
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.newDocument();
    Element body = doc.createElement("body");
    body.appendChild(doc.createElement("elem1"));
    Now I need to retrive this xml as String, but how? The only sample I found, is XMLUtils class from axis libs, which have method DocumentToString. But may be such functionality can be found in classes that are in standart jdk pacjkages? If not, how can I receive xml as string using this XMLUtils, without header "xml version="1.0" encoding="UTF-8""?
    Thanks,
    Stan

    Hi Stan,
    When I was using DOM, I remember having converted my document to a String simply with the "toString()" method ... I know it may sound a bit easy, but have you tried it ?
    Else, I don't know if your application has to respect some performance rules, but DOM is one of the worst API in terms of memory consumption.
    You should take a look at some other, like XMLBeans if you want a XSD strong related scheme.
    Well, I hope you'll find a solution
    See ya !

  • Covert DOM element to String

    It sounds very simple, however could not find any solution using JAXP.
    What I need is that I have a DOM element, I want to convert the DOM element into String and store into the database. I used to do it using JDOM. It has a feature something like toString.
    I know that serialization is another option, however, want to know how to do this way.

    xmlString.getBytes()No, that causes your problem. Read the documentation to see what the getBytes() method does. Here's what you should do instead:Document document = documentBuilder.parse(new InputSource(new StringReader(xmlString)));This doesn't convert from String to bytes using a bad encoding. But you also say:
    xmlString contains Japanese characters and was originally from a xml file with UTF-8 encoing.In this case there's a good chance that in reading from the file to the String you have also failed to use UTF-8 to do the decoding. Why not just pass a File object to the parser and let it deal with the encoding issues? It knows what to do.

Maybe you are looking for

  • LR2.3/Vista: why won't it auto open when camera is plugged in?

    Dear All: My LR1.4 used to automatically open whenever i plug in (via usb) a camera, very convenient. i've upgraded to LR2.3, and all seems to be fine. i just bought a brand new Fuji F200EXR camera, and somehow, "autoplay" does open (that's a Vista a

  • Is there a network version of Adobe Acrobat Pro 9?

    Is there a network version of Adobe Acrobat Pro 9?  If not, are their volume licenses available? What additional adobe products need to be purchased in order to run Adobe Acrobat 9 on a network? Is there a licensing system that allows, for example, 4

  • How to embed more than 393 chars in form fields

    how to embed more than 1000 character in the field. I have written a xsl template which is about 2 pages in length. How do I embed it in the word template fields.

  • Dead loop in formula node

    Hi, I have encountered the following problem in a formula node. Everything seems simple and right. But there is no output and the loop goes on forever. The sizes of both input arrays are the same. Need your advice. Thanks. Rut Attachments: Algorithm.

  • Samba As Windows PDC problem + AD

    Hello All, In an effort to minimize the amount of different logins my users have, I am trying to create a windows domain with Samba as a PDC in OSX Server 10.6.6. Before attempting to "create" this domain Samba was running on the server as a "Standal