Writing Dom tree from JAXP

Once I build a DOM tree, how can I write the xml to a string or a file using
the JAXP API. Given any particular Parser implementation, I have been able
to find methods that allow me to write the xml. However, from the java api
(JAXP), there doesn't seem to be a mechanism for doing this. Please
advise...
regards,
todd

Hi Todd,
You can't write XML out using JAXP 1.0 -- that feature is not included in
the API.
But you can use the XML serialization package that is included in the
built-in parser and the bundled Apache Xerces parser. Check out the
weblogic.apache.xml.serialize, org.apache.xml.serialize packages. The
javadocs are at
http://www.weblogic.com/docs60/xerces/org/apache/xml/serialize/package-summa
ry.html
Cheers,
-Todd
"Todd Singleton" <[email protected]> wrote in message
news:3a2d5bdb$[email protected]..
Once I build a DOM tree, how can I write the xml to a string or a fileusing
the JAXP API. Given any particular Parser implementation, I have beenable
to find methods that allow me to write the xml. However, from the javaapi
(JAXP), there doesn't seem to be a mechanism for doing this. Please
advise...
regards,
todd

Similar Messages

  • Unparsing a DOM tree and write XML to file

    Hi,
    I have created a DOM tree from scratch and would like to unparse the DOM tree and write the XML to a file, but how do I do that?
    Does anybody got code examples that do this?
    All help are very appreciated!
    /Daniel

    Thank you very much for the hint! Unfortunaly I still got problem to get it work though.
    I made a little piece of test code to try it but during the execution of the "Transformer.transform(source,result)" method I gets an "org.w3c.dom.DOMException".
    Does anybody see what that problem might be cause of by exmining the code below?
    I also would like to know how to specify the location where I would like to print out the XML file.
    Here is my little piece of test code:
    try{
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFadctory.newInstance();
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    Document doc = docBuilder.newDocument();
    doc.appendChild(doc.createElement("topLevel"));
    Element elm = doc.getDocumentElement();
    elm = (Element)elm.appendChild(doc.createElement("PersonData"));
    elm = (Element)elm.appendChild(doc.createElement("Name"));
    elm.setAttribute("Firstname","D");
    elm.setAttribute("Lastname", "D");
    DOMResult result = new DOMResult(doc);
    DOMSource source = new DOMSource(doc);
    TransformerFactory transformerFactory = TansformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.transform(source,result);
    }catch(ParserConfigurationException e) {
    }catch(IOException e) {
    }catch(TransformerException te) {

  • Help with creating a new XML file from an existing DOM tree!!

    i want to create a new XML file from an existing DOM tree
    i used this code to create a new document:
    static public Document createDocument(String fileName) throws ParserConfigurationException//,IOException,SAXException
              try {
                   DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                   factory.setIgnoringComments(true);
                   factory.setIgnoringElementContentWhitespace(true);
                   factory.setValidating(true);
                   DocumentBuilder builder =factory.newDocumentBuilder();
                   return builder.newDocument();
    //          handle exception creating DocumentBuilder
              catch ( ParserConfigurationException parserError ) {
                        throw new ParserConfigurationException();
              }then i used this code to transform the DOM :
    public void exportDocument(Document document) {
              try {
                   Source xmlSource = new DOMSource( document );
                   Result result = new StreamResult( System.out );
                   TransformerFactory transformerFactory =
                        TransformerFactory.newInstance();
                   Transformer transformer =transformerFactory.newTransformer();
                   transformer.setOutputProperty( "indent", "yes" );
                   transformer.transform( xmlSource, result );
           //then catching the exceptions
    But the file was not created and i didn't find where can i specify the DTD that the XML file should use and where can i enter the name of the XML file itself
    Another questoin can i write a DTD file dynamically during the execution of the program??

    Cross-post: http://forum.java.sun.com/thread.jspa?threadID=784467&messageID=4459240#4459240

  • Generate an XML file from a DOM tree

    Hi,
    I'm trying to generate an XML file from a DOM tree that I obtained from another XML file with the Xerces library. I used the following operation :
    public static void writeXmlFile(Document doc, String filename) {
    try {
    Source source = new DOMSource(doc);
    File file = new File(filename);
    Result result = new StreamResult(file);
    Transformer xformer = TransformerFactory.newInstance().newTransformer();
    xformer.transform(source, result);
    } catch (TransformerConfigurationException e) {
    System.err.println(e);
    System.exit(1);
    } catch (TransformerException e) {
    System.err.println(e);
    System.exit(1);
    But I have this Windows/Linux problem. When I execute this on Windows, everything is correct. But if I try on Linux (every distribution does the same thing), I obtain an XML file where everything is written on just ONE LINE : there is neither identation nor carriage return at the end of a line ... And that is pretty annoying 'cause I need to SEE what I generate ...
    Thanks for your answer,
    Blueberryfin.

    Actually I would think that no indents and no new-lines would be more correct, but maybe it's an option for parsers to do it either way if you don't specify it. If you want to specify it, look at this post from last month:
    http://forum.java.sun.com/thread.jsp?forum=34&thread=383400

  • How to create a new DOM tree with nodes from another DOM tree?

    Hello,
    I would like to create a DOM tree by using nodes from an existing DOM. How can I do that? I tried with appendChild and it gaves me as error: "WRONG_DOCUMENT_ERR".
    Thx!

    The xml that should be parsed is something like that:
    <?xml version="1.0" encoding="UTF-8"?>
    <root xmlns="http://www.nebi.biz/schemas/bd/nebienvelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" BusinessDocumentVersion="7.0" xsi:schemaLocation="http://www.nebi.biz/schemas/bd/nebienvelope NeBiEnvelope_L_0_3.xsd">
        <Header>
            <To>
                <OrganisationId>OrganisationId0</OrganisationId>
                <DestinationType>DestinationType0</DestinationType>
                <Destination>Destination0</Destination>
            </To>
            <From>
                <OrganisationId>OrganisationId1</OrganisationId>
                <DestinationType>DestinationType1</DestinationType>
                <Destination>Destination1</Destination>
            </From>
            <Dialog>Dialog0</Dialog>
            <DialogId>DialogId0</DialogId>
            <MessageType>MessageType0</MessageType>
            <MessageId>MessageId0</MessageId>
            <Reference Role="buyer" Type="BusinessAgreement">Reference0</Reference>
            <SequenceId>SequenceId0</SequenceId>
            <Checksum Type="MD5">Checksum0</Checksum>
        </Header>
        <Body>
            <Order xmlns="http://www.nebi.biz/schemas/bd/order" BusinessDocumentVersion="7.0" OrderType="request" xsi:schemaLocation="http://www.nebi.biz/schemas/bd/order Order_L_0_96.xsd">
                <OrderId Role="buyer"/>
                <ProductLine Number="1">
                    <ProductUseCaseDetails Id="WICreation">
                        <wiCreation xmlns="http://mydomain.com/GRIPP/workitem">
                            <wiCreationHeader>
                                <userId>wmadm</userId>
                                <taskModelName>DNS02_CreateMasterZone</taskModelName>
                            </wiCreationHeader>
                            <wiCreationBody>
                                <DNS02CreationBody>
                                    <GlobalSection xmlns="http://mydomain.com/GRIPP/dns02">
                                        <Outcome>1</Outcome>
                                    </GlobalSection>
                                    <SpecificSection xmlns="http://mydomain.com/GRIPP/dns02">
                                        <Zonename>0.0</Zonename>
                                        <RRLocation>Domain</RRLocation>
                                        <RemoteSlaves type="multiline">
                                            <RemoteSlaveFQDN>test.com</RemoteSlaveFQDN>
                                            <RemoteSlaveIP>123.234.234.123</RemoteSlaveIP>
                                            <RemoteSlaveFQDN>test.net</RemoteSlaveFQDN>
                                            <RemoteSlaveIP>123.123.123.123</RemoteSlaveIP>
                                        </RemoteSlaves>
                                    </SpecificSection>
                                </DNS02CreationBody>
                            </wiCreationBody>
                        </wiCreation>
                    </ProductUseCaseDetails>
                </ProductLine>
             </Order>
        </Body>
        <Trace>
            <CheckPoint>
                <SystemName>SystemName0</SystemName>
                <SystemDateTime>2006-05-04T18:13:51.0Z</SystemDateTime>
            </CheckPoint>
        </Trace>
    </root>This is the output of the Document after parsing and augmentation with the Xerces parser.

  • Generating XML from DOM tree

    Hello,
    I am trying to generate a XML file from a DOM tree. This facility is there in IBM parser.
    But anyone can help me out in generating a XML file or string from a DOM tree using the Crimson parser provided by default in JDK 1.4.0
    Thank you

    The only way I know is to use JDOM (which provides a output package).
    You can build a JDOM tree starting from your DOM tree, and then output this JDOM tree in an XML file.
    Hope it will help.

  • Getting the absolute text position from a DOM tree

    Does anybody knows how to get the absolute text position of a node inside the DOM tree? Is there any DOM implementation that keep track of the absolute text position of each Node element or I need to overload somo methods by hand?
    Regards,
    Daniel Oliveira

    The position() function in XSLT returns the order of the element.
    For an xml document with elements:
    <a>
    <b></b>
    <b></b>
    </a>
    <xsl:apply-templates select="b"/>
    <xsl:template match="b">
    Element b:
    <xsl:value-of select="position()"/>
    </xsl:template>

  • How to modify a node value in a DOM tree?

    I have following code; it parses a XML file from a file and builds a in-memory DOM tree, but when I tries to modify one of the node value, it keeps telling me: oracle.xml.parser.v2.XMLDOMException: Node cannot be modified. How do I do it?
    // ==================================
    DOMParser theParser = new DOMParser();
    theParser.setValidationMode(false);
    InputStream theInputStream = myApp.class.getResourceAsStream("/test.xml");
    theParser.parse(theInputStream);
    XMLDocument theXMLDoc = theParser.getDocument();
    NodeList theNodeList = theXMLDoc.selectNodes("/root/child");
    for (int i = 0; i < theNodeList.getLength(); i++)
    theNodeList.item(i).setNodeValue("test");
    null

    You're trying to set the node value of an element, which cannot have a node value.
    You need to set the node value of the text-node child of the element instead.
    Or remove the current text-node child and append a new text-node child with the new value.

  • Applescript Help: Search for text in Safari DOM tree

    Im trying to make a script really similar what was asked here: Re: Find text in webpage and email notification applescript/automator Except instead of searching the "source code" of the page, I want the script to search the "DOM tree" for the page.
    To summarize, I am trying to make a script that loads a safari page, searches for a particular text in the DOM Tree, and if found will send me an email.
    Here is the code from the other thread I referenced:
    on idle
              set pagURL to "http://page.url.com?whatever"
              if application "Safari" is not running then
                        quit
                        return
              end if
              tell application "Safari"
                        set URL of document 1 of window 1 to "http://your.web.address/"
                        delay 5
      -- delay to let page load.
                        if source of document 1 of window 1 contains "search text" then
                                  my sendAMail()
                        end if
                        return 900 --fifteen minutes
              end tell
    end idle
    on sendAMail()
              tell application "Mail"
                        set theMess to make new outgoing message at end with properties {sender:"your name", subject:"some subject line", content:"The message you want to send to yourself", visible:true}
                        tell theMess
                                   make new to recipient at end of to recipients with properties {address:"[email protected]"}
                        end tell
      -- send theMess
              end tell
    end sendAMail
    Any help would be appreciated!

    For the URL you quote as an example (http://www.sislands.com/coin70/week2/NestedLoops1.htm), using text instead of source worked for me:
    if text of document 1 of window 1 contains "1  2  3  4" then
    another example:
    if text of document 1 of window 1 contains "10 12 14 16" then
    Note a double space between single digits (1  2  3  4) and a single space between double digits (10 12 14 16) is required for a match as per the table format:
    Any full line:
    if text of document 1 of window 1 contains "for (i = 1; i <= 10; i++) { // when i = 10" then
    or partial line works:
    if text of document 1 of window 1 contains "; i++) { // when i = 10" then

  • XML : Transform DOM Tree to XML String in an applet since the JRE 1.4.2_05

    Hello,
    I build a DOM tree in my applet.
    Then I transform it to XML String.
    But since the JRE 1.4.2_05 it doesn't work.
    These lines failed because these variables became final:
    org.apache.xalan.serialize.CharInfo.XML_ENTITIES_RESOURCE = getClass().getResource("XMLEntities.res").toString();
    org.apache.xalan.processor.TransformerFactoryImpl.XSLT_PROPERTIES = getClass().getResource("XSLTInfo.properties").toString();The rest of the code :
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = domFactory.newDocumentBuilder();
    Document domXML = builder.newDocument();
    // I build my DOM Tree
    StringWriter xmlResult = new StringWriter();
    Source source = new DOMSource(domXML);
    Result result = new StreamResult(xmlResult);
    Transformer xformer = TransformerFactory.newInstance().newTransformer();
    xformer.setOutputProperty(javax.xml.transform.OutputKeys.INDENT,"yes");
    xformer.transform(source,result);Is there any other way to get an XML String from a DOM tree in an applet ?
    I'm so disappointed to note this big problem.

    Does anyone have an idea why I get this error message when try to use transform in an applet?
    Thanks...
    java.lang.ExceptionInInitializerError
         at java.lang.Class.forName0(Native Method)
         at java.lang.Class.forName(Unknown Source)
         at org.apache.xalan.serialize.SerializerFactory.getSerializer(Unknown Source)
         at org.apache.xalan.transformer.TransformerIdentityImpl.createResultContentHandler(Unknown Source)
         at org.apache.xalan.transformer.TransformerIdentityImpl.transform(Unknown Source)
         at matrix.CreateMtrx.SaveDoc(CreateMtrx.java:434)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
         at java.lang.reflect.Method.invoke(Unknown Source)
         at thinlet.Thinlet.invokeImpl(Unknown Source)
         at thinlet.Thinlet.invoke(Unknown Source)
         at thinlet.Thinlet.handleMouseEvent(Unknown Source)
         at thinlet.Thinlet.processEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)
    Caused by: java.lang.RuntimeException: The resource [ XMLEntities.res ] could not load: java.net.MalformedURLException: no protocol: XMLEntities.res
    XMLEntities.res      java.net.MalformedURLException: no protocol: XMLEntities.res
         at org.apache.xalan.serialize.CharInfo.<init>(Unknown Source)
         at org.apache.xalan.serialize.SerializerToXML.<clinit>(Unknown Source)
         ... 28 more

  • Schema validation error when validating dom tree in memory

    Hello folks,
    I have the following problem:
    I construct a xml-file via the DOM API and before writing to file, I want to validate the DOM tree against a existing schema file.
    But I always receive following error:
    In line 0 of buffer:
    LSX-00006: No default namespace for "conf_file"
    Validation failed, error 6
    Here's what the xml file looks like:
    <conf_file xmlns="http://www.sun.com/gridware/configuration_file_format" >
    <conf_version>0</conf_version>
    <conf_entry>
    <param>test</param>
    <value>0</value>
    </conf_entry>
    </conf_file>
    The curious thing about that is, when first writing the DOM tree to file via printStream() and then validating the written xml file againstr the schema everything works fine.
    Do you know what I doing wrong ?
    Thanks ...
    Harti

    It is a bug.

  • XML Parser for Java v2. Applying XSLT to DOM tree

    I encountered pretty weird behavior of XML Parser for Java v2.
    While applying XSLT to XML document created in memory using DOM
    interface I couldn't access element attributes. For example,
    given the XML document:
    <root>
    <Item ID="00001">Value of Item 00001</Item>
    <Item ID="00002">Value of Item 00002</Item>
    </root>
    and XSLT:
    <xsl:template match="/">
    <HTML>
    <HEAD>
    <TITLE>XSLT Test</TITLE>
    </HEAD>
    <BODY>
    <xsl:for-each select="/Error">
    <H1>Error</H1><xsl:value-of select="."/>
    </xsl:for-each>
    <TABLE border="0" cellspacing="0" cellpadding="2">
    <TBODY>
    <xsl:for-each select="/root">
    <TR>
    <TH style="background-color:khaki">
    <xsl:text>Attribute</xsl:text>
    </TH>
    <TH style="background-color:khaki">
    <xsl:text>Value</xsl:text>
    </TH>
    </TR>
    <xsl:for-each select="Item">
    <TR>
    <TD><xsl:value-of select="@ID"/></TD>
    <TD><xsl:value-of select="."/></TD>
    </TR>
    </xsl:for-each>
    </xsl:for-each>
    </TBODY>
    </TABLE>
    </BODY>
    </HTML>
    </xsl:template>
    If I build DOM tree by parsing XML file the resulting HTML
    document after applying XSLT will display
    Attribute Value
    00001 Value of Item 00001
    00002 Value of Item 00002
    But if I build DOM tree using following code:
    XMLDocument xDoc = new XMLDocument();
    Element root = xDoc.createElement( "root" );
    xDoc.appendChild( root );
    Element elem = xDoc.createElement( "Item" );
    elem.setAttribute( "ID", "00001" );
    root.appendChild( elem ).
    appendChild( xDoc.createTextNode( "Value of Item 00001" ) );
    elem = xDoc.createElement( "Item" );
    elem.setAttribute( "ID", "00002" );
    root.appendChild( elem )
    .appendChild( xDoc.createTextNode( "Value of Item 00002" ) );
    the same XSLT will produce the following HTML output:
    Attribute Value
    Value of Item 00001
    Value of Item 00002
    So the value for the ID attribute is not displayed. At the same
    time I can access this attribute using DOM interface. For
    example, following code
    NodeList nList = xDoc.getElementsByTagName( "Item" );
    Element e;
    for( int i = 0; i < nList.getLength(); i++ )
    e = (Element)nList.item( i );
    System.out.println( "ID: " + e.getAttribute( "ID" ) );
    produces an output
    ID: 00001
    ID: 00002
    Here is the code for applying XSLT to DOM tree:
    DOMParser parser = new DOMParser();
    parser.parse( new FileInputStream( "test.xsl" ) );
    XMLDocument xsldoc = parser.getDocument();
    XSLStylesheet xsl = new XSLStylesheet( xsldoc, createURL( "" ) );
    XMLDocument out = new XMLDocument();
    out.appendChild( new XSLProcessor().processXSL(xsl, xDoc) );
    out.print( new FileOutputStream( "test.html" ) );
    Andrei Filimonov
    null

    We are not getting what you're getting on Solaris. See the
    following:
    Script started on Tue Jun 22 18:53:56 1999
    Processing /view/test/vobs/oracore3/.ndeprodrc.csh
    Processing /private/.nderc.csh
    [test] > cat bruno.xml
    <my_grandpa age="88">
    <my_dad age="66">
    <me age="44">
    <my_son age="22">
    </my_son>
    </me>
    </my_dad>
    </my_grandpa>
    [test] > cat bruno.xsl
    <?xml version="1.0"?>
    <!-- Identity transformation -->
    <xsl:stylesheet xmlns:xsl="http://www.w3.org/XSL/Transform/1.0">
    <xsl:template match="me">
    <xsl:value-of select="my_son/@age"/>
    <xsl:value-of select="@age"/>
    <xsl:value-of select="../@age"/>
    <xsl:value-of select="../../@age"/>
    </xsl:template>
    </xsl:stylesheet>
    [test] > java XSLSample bruno.xsl bruno.xml
    <root>
    22446688
    </root>
    [test] > exit
    script done on Tue Jun 22 18:54:22 1999
    What platform are you on and does your stylesheet and xml doc
    match ours?
    Oracle XML Team
    http://technet.oracle.com
    Oracle Technology Network
    Bruno Bontempi (guest) wrote:
    : I had a similar problem in accessing element attributes from
    an
    : XSLT sheet.
    : It seems like the processor correctly accesses element
    attributes
    : in the context node, but does not retrieve values of
    attributes
    : outside the context node.
    : For example, for an XML document like:
    : <my_grandpa age="88">
    : <my_dad age="66">
    : <me age="44">
    : <my_son age="22">
    : </my_son>
    : </me>
    : </my_dad>
    : </my_grandpa>
    : and an XSL stylesheet like:
    : <xsl:template match="me">
    : <xsl:value-of select="my_son/@age"/>
    : <xsl:value-of select="@age"/>
    : <xsl:value-of select="../@age"/>
    : <xsl:value-of select="../../@age"/>
    : </xsl:template>
    : I expect an output like:
    : 22446688
    : but all I get is
    : 44
    : I am also using Jim Clark's XT, which is returning the
    expected
    : result.
    : Thanks in advance for your help,
    : Bruno.
    : Andrei Filimonov (guest) wrote:
    : : I encountered pretty weird behavior of XML Parser for Java
    v2.
    : : While applying XSLT to XML document created in memory using
    DOM
    : : interface I couldn't access element attributes. For example,
    : : given the XML document:
    : : <root>
    : : <Item ID="00001">Value of Item 00001</Item>
    : : <Item ID="00002">Value of Item 00002</Item>
    : : </root>
    : : and XSLT:
    : : <xsl:template match="/">
    : : <HTML>
    : : <HEAD>
    : : <TITLE>XSLT Test</TITLE>
    : : </HEAD>
    : : <BODY>
    : : <xsl:for-each select="/Error">
    : : <H1>Error</H1><xsl:value-of select="."/>
    : : </xsl:for-each>
    : : <TABLE border="0" cellspacing="0" cellpadding="2">
    : : <TBODY>
    : : <xsl:for-each select="/root">
    : : <TR>
    : : <TH style="background-color:khaki">
    : : <xsl:text>Attribute</xsl:text>
    : : </TH>
    : : <TH style="background-color:khaki">
    : : <xsl:text>Value</xsl:text>
    : : </TH>
    : : </TR>
    : : <xsl:for-each select="Item">
    : : <TR>
    : : <TD><xsl:value-of select="@ID"/></TD>
    : : <TD><xsl:value-of select="."/></TD>
    : : </TR>
    : : </xsl:for-each>
    : : </xsl:for-each>
    : : </TBODY>
    : : </TABLE>
    : : </BODY>
    : : </HTML>
    : : </xsl:template>
    : : If I build DOM tree by parsing XML file the resulting HTML
    : : document after applying XSLT will display
    : : Attribute Value
    : : 00001 Value of Item 00001
    : : 00002 Value of Item 00002
    : : But if I build DOM tree using following code:
    : : XMLDocument xDoc = new XMLDocument();
    : : Element root = xDoc.createElement( "root" );
    : : xDoc.appendChild( root );
    : : Element elem = xDoc.createElement( "Item" );
    : : elem.setAttribute( "ID", "00001" );
    : : root.appendChild( elem ).
    : : appendChild( xDoc.createTextNode( "Value of Item
    00001" )
    : : elem = xDoc.createElement( "Item" );
    : : elem.setAttribute( "ID", "00002" );
    : : root.appendChild( elem )
    : : .appendChild( xDoc.createTextNode( "Value of Item
    00002" )
    : : the same XSLT will produce the following HTML output:
    : : Attribute Value
    : : Value of Item 00001
    : : Value of Item 00002
    : : So the value for the ID attribute is not displayed. At the
    same
    : : time I can access this attribute using DOM interface. For
    : : example, following code
    : : NodeList nList = xDoc.getElementsByTagName( "Item" );
    : : Element e;
    : : for( int i = 0; i < nList.getLength(); i++ )
    : : e = (Element)nList.item( i );
    : : System.out.println( "ID: " + e.getAttribute( "ID" ) );
    : : produces an output
    : : ID: 00001
    : : ID: 00002
    : : Here is the code for applying XSLT to DOM tree:
    : : DOMParser parser = new DOMParser();
    : : parser.parse( new FileInputStream( "test.xsl" ) );
    : : XMLDocument xsldoc = parser.getDocument();
    : : XSLStylesheet xsl = new XSLStylesheet( xsldoc, createURL
    : : XMLDocument out = new XMLDocument();
    : : out.appendChild( new XSLProcessor().processXSL(xsl, xDoc) );
    : : out.print( new FileOutputStream( "test.html" ) );
    : : Andrei Filimonov
    null

  • Serialization of DOM Tree+calling POST method in servlet

    Hi all,
    I am trying to serialize a DOM tree and send it from an applet to a servlet..I am having difficulty in calling the post method of the servlet..can anyone please tell me how the POST method in the servlet is called from the applet...I am using the code as seen on the forum for calling the POST method as below:
    URL url = new URL("http://localhost:8080/3awebapp/updateservlet");
    HttpURLConnection con = (HttpURLConnection)url.openConnection();
    con.setUseCaches(false);
    con.setRequestProperty("Content-Type","application/octet-stream");
    System.out.println("Connected");
    con.setDoOutput(true);
    con.setRequestMethod("POST");
    System.out.println("do output called");
    con.setDoInput(true);
    System.out.println("do Input called");
    ObjectOutputStream objout = new ObjectOutputStream(con.getOutputStream());
    yet the post method in the servlet does not seem to be called....
    another problem I had was trying to serialize a DOM document and send it to the servlet. I am using the following code to write the DOM document on an output stream..would this work:
    OutputFormat format = new OutputFormat(document);
    XMLSerializer serializer = new XMLSerializer( objout, format );
    System.out.println("XML Serializer Started");
    DOMSerializer newSerializer=serializer.asDOMSerializer();
    newSerializer.serialize( document );
    objout.flush();
    objout.close();
    ...since the doPost method of the servlet is not being called I do not whether the above code would be sent to the servlet..
    Any advice on the above two matters would be highly appreciated..
    Fenil

    perhaps my piece of code may help You - relevant parts marked //<--,
    but I have a problem when reading my object - which is a serialized DomTree :
    Variant 1 : sending XML-data as string will arrive as should be, but parser says org.xml.sax.SAXParseException (missing root-element)
    Variant 2 : readObject says java.io.OptionalDataException, but the DomTree will be parsed and displayed
    -- snipp --
    import java.io.InputStream;
    import org.w3c.dom.Document;
    import java.net.*;
    import com.oreilly.servlet.HttpMessage; //<--
    import java.util.*;
    import java.io.ObjectInputStream;
    myApplet :
    try {
         URL url = new URL(getCodeBase(),"../../xml/FetchDocument");
         HttpMessage msg = new HttpMessage(url);
         Properties props = new Properties();
         props.put("InputFeldName","FeldWert");
         InputStream in = msg.sendGetMessage(props);
    //<-- alt : sendPostMessage
         ObjectInputStream result = new ObjectInputStream(in);
         try {
         Object obj = result.readObject();
    myServlet :
    public void doGet(HttpServletRequest req,HttpServletResponse res)
         throws ServletException, IOException {
    TreeCreator currentTree = new TreeCreator();
    ObjectOutputStream out = new ObjectOutputStream(res.getOutputStream());
    -- variant 1 :
    out.writeObject(currentTree.skillOutputString());
    out.flush();
    out.close();
    -- variant 2 :          
    OutputFormat( TreeCreator.cdi ); //Serialize DOM
    OutputFormat format = new OutputFormat( currentTree.getCDI() ); format.setEncoding("ISO-8859-1");
    XMLSerializer serial = new XMLSerializer( out, format );
    serial.asDOMSerializer(); // As a DOM Serializer
    serial.serialize( currentTree.getCDI().getDocumentElement() );
    serial.endDocument();
    out.flush();
    out.close();

  • Error when I replaced  the DOM parcer with JAXP

    I replaced the DOM parcer with JAXP ....
    We moved from DOM parcer �import org.apache.xerces.parsers.DOMParser;� to JAXP.
    Here is my code:
    // Step 1: create a DocumentBuilderFactory and setNamespaceAware
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    // Step 2: create a DocumentBuilder
      DocumentBuilder db = dbf.newDocumentBuilder();
    // Step 3: parse the input file to get a Document object
    Document doc = db.parse(location);
      root = doc.getDocumentElement();
      root.normalize();
    AND when we run stress test after a while we start getting error
    java.lang.NullPointerException
    at org.apache.xerces.dom.DeepNodeListImpl.nextMatchingElementAfter(Unknown Source)
    at org.apache.xerces.dom.DeepNodeListImpl.item(Unknown Source)
    at org.apache.xerces.dom.DeepNodeListImpl.getLength(Unknown Source)
    at com.xxx.yyy.WfStartTasksXmlDAO.getActionPerformed(Unknown Source)
    at com.xxx.yyy.WfStartTasksXmlDAO.getAction(Unknown Source)
    - Any idea why we are getting this error. Is this server (Linux) problem? or JAXP?
    Message was edited by:
    TamerBasha

    This is happening because JAXP is not thread safe. need to synchronize bracket or use thread safe parser.

  • How i can store a DOM Tree to XML file

    I want to insert a xml documet into another another xml document and then store it.
    for this i have parsed a xml document using com.sun.xml.parser and got its domtree in document doc1 by builder.getDocument(). After that i parsed another xml document and got it's domtree in document doc2 by builder.getDocument().
    now i created a Document type doc . I create dom tree in doc that contains all the nodes of doc1 and insert the doc2 at a position . If i m printing this doc i got the required document. Now i want to store this doc into a xml file. so i paas thid doc and filename in which i want to store it into a function
    public static void writeXmlToFile(String filename, Document document)
    try
                   // Prepare the DOM document for writing
         Source source = new DOMSource(document);
         // Prepare the output file
         File file = new File(filename);
         Result result = new StreamResult(file);
    // Write the DOM document to the file
         // Get Transformer
         Transformer xformer = TransformerFactory.newInstance().newTransformer();
              // Write to a file
         xformer.transform(source, result);
    catch (TransformerConfigurationException e)
         System.out.println("TransformerConfigurationException: " + e);
    catch (TransformerException e)
         System.out.println("TransformerException: " + e);
    but i m getting following error
    Exception in thread "main" java.lang.AbstractMethodError: com.sun.xml.tree.ElementNode.getNamespacesURI()Ljava/lang/String;
    at com.sun.apache.xalan.internal.xsltc.trax.DOM2TO.parse(Unknown Source)
    at com.sun.apache.xalan.internal.xsltc.trax.DOM2TO.parse(Unknown Source)
    at com.sun.apache.xalan.internal.xsltc.trax.DOM2TO.parse(Unknown Source)
    at com.sun.apache.xalan.internal.xsltc.trax.TranformerImpl.transformIdentity(Unknown Source)
    at com.sun.apache.xalan.internal.xsltc.trax.TranformerImpl.transformIdentity(Unknown Source)
    at com.sun.apache.xalan.internal.xsltc.trax.TranformerImpl.transformIdentity(Unknown Source)

    thanks for the reply
    i m able to do my job using
    import javax.xml.parsers.*;
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder1 = factory.newDocumentBuilder();
         doc = builder1.parse(uri);
    when i want to covert this doc into an xml file by passing this doc in the function below then it is ok..
    public static void writeXmlToFile(String filename, Document document)
    try
    // Prepare the DOM document for writing
    Source source = new DOMSource(document);
    // Prepare the output file
    File file = new File(filename);
    Result result = new StreamResult(file);
    // Write the DOM document to the file
    // Get Transformer
    Transformer xformer = TransformerFactory.newInstance().newTransformer();
    // Write to a file
    xformer.transform(source, result);
    catch (TransformerConfigurationException e)
    System.out.println("TransformerConfigurationException: " + e);
    catch (TransformerException e)
    System.out.println("TransformerException: " + e);
    but i want to use com.sun.xml.parser like
    import com.sun.xml.parser.*;
    import com.sun.xml.tree.XmlDocumentBuilder;
    XmlDocumentBuilder builder = new XmlDocumentBuilder();
    Parser parser = new com.sun.xml.parser.Parser();
    parser.setDocumentHandler(builder);
    builder.setParser(parser);
    builder.setDisableNamespaces(false);
    parser.parse(uri);
    doc = builder.getDocument();
    when i m trying to store this doc into an xml file by passing this doc into funtion writeXmlToFile( filename, doc) then the errors occur (that i hav told in the first post)
    plz help..

Maybe you are looking for