DOM document problem

Hello,
We created webservice based on example EchoDom. When we post
XML document (where elements have attributes) to webservice, then the following
excetption occurs:
weblogic.xml.stream.XMLStreamException: ':' expected a valid beginning name character
- with nested exception:
[Error at line:2 col:8  ':' expected a valid beginning name character]
javax.xml.soap.SOAPException: failed to receive message:
at weblogic.webservice.core.DefaultWebService.invoke(DefaultWebService.java:218)
at weblogic.webservice.server.servlet.ServletBase.serverSideInvoke(ServletBase.java:362)
at weblogic.webservice.server.servlet.WebServiceServlet.serverSideInvoke(WebServiceServlet.java:269)
at weblogic.webservice.server.servlet.ServletBase.doPost(ServletBase.java:346)
at weblogic.webservice.server.servlet.WebServiceServlet.doPost(WebServiceServlet.java:237)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:760)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
at weblogic.servlet.internal.ServletStubImpl$ServletInvocationAction.run(ServletStubImpl.java:1058)
at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:401)
at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:306)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:5412)
at weblogic.security.service.SecurityServiceManager.runAs(SecurityServiceManager.java:744)
at weblogic.servlet.internal.WebAppServletContext.invokeServlet(WebAppServletContext.java:3086)
at weblogic.servlet.internal.ServletRequestImpl.execute(ServletRequestImpl.java:2544)
at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:153)
XML is quite simple for illustrative purposes:
<test>
<data Id="D1"/>
</test>
If we remove attributes
<test>
<data>some data</data>
</test>
then everything works fine.
Does anybody know the solution to that problem?
Ago

On Mon, 10 Feb 2003 08:34:23 -0800, Ago Meister wrote:
>
Hello,
We created webservice based on example EchoDom. When we post
XML document (where elements have attributes) to webservice, then the following
excetption occurs:Can you please run with the system property weblogic.webservice.verbose
set to true and post the request and response xml?

Similar Messages

  • 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

  • Problem casting org.w3c.dom.Document to oracle.xml.parser.v2.XMLDocument

    I have the following problem:
    I get my xml-documents as an XMLType from the database and want to compare these using the supplied Oracle class oracle.xml.differ.XMLDiff (i use the java version supplied with Oracle 9i r2).
    XMLType.getDOM() returns the xml-document as a org.w3c.dom.Document,
    what i need for oracle.xml.differ.XMLDiff is a oracle.xml.parser.v2.XMLDocument.
    How can i cast/convert between these two formats?
    thanks!
    p.s. cross-posting with Re: Casting/Converting XMLType to XMLDocument? (but i think this forum is more relevant).

    Hi,
    thanks for the suggestion: i have written the code shown below. It results in a casting error.
    As far as i know, i don't use a oracle.xdb.dom.XDBDocument, i only use a oracle.xdb.XMLType as the input parameter for my conversion-method:
    any new suggestions ???
    p.s. the second method which is commented does work, but is a bit verbose.
       private static oracle.xml.parser.v2.XMLDocument convert2XMLDocument(XMLType xml) {
         // simple version (should work according to tech. doc. 9i r2/ 10g r1 database)
         oracle.xml.parser.v2.XMLDocument doc = null;
         try {
            // n.b. probleem is dat XMLType.getDOM() een w3c.Document object teruggeeft ipv een oracle.XMLDocument.
            System.out.println("convert2XMLDocument(): casting w3c.Document naar oracle.XMLDocument.");
            doc = (oracle.xml.parser.v2.XMLDocument) xml.getDOM(); // public org.w3c.dom.Document getDOM()
            System.out.println("convert2XMLDocument(): done casting w3c.Document naar oracle.XMLDocument.");
         catch (Exception e) {
            e.printStackTrace(System.out);
        return doc;
       private static XMLDocument convert2XMLDocument(XMLType xml) {
         // complex version: works ok !!!
         XMLDocument doc = null;
         try{
            DOMParser parser  = new DOMParser();
            parser.setValidationMode(oracle.xml.parser.v2.XMLParser.NONVALIDATING);
            parser.setPreserveWhitespace (true);   
            parser.parse(new StringReader(xml.getStringVal()));
            doc = parser.getDocument();
        catch ( XMLParseException e ) {
          e.printStackTrace(System.out);
        catch ( SQLException e ) {
          e.printStackTrace(System.out);
        catch ( Exception e ) {
          e.printStackTrace(System.out);
        return doc;
    convert2XMLDocument(): casting w3c.Document naar oracle.XMLDocument.
        java.lang.ClassCastException: oracle.xdb.dom.XDBDocument
         at pnb.bdb.xml.testJDBC.convert2XMLDocument(testJDBC.java:305)
         at pnb.bdb.xml.testJDBC.main(testJDBC.java:187)

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

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

  • DOM Parsing problems... (newbie in trouble)

    I am trying to get a DOM Parser contruct a DOM Object from an XML file... I am having trouble getting the code validate against my XML Schema: <p>
    <?xml version="1.0" encoding="UTF-8"?> <
    <!-- edited with XML Spy v4.4 U (http://www.xmlspy.com) by Fedro E. Ponce de Leon Luengas (ASI Consulores, S.A. de C.V.) -->
    <xs:schema targetNamespace="http://palaciohierro.com.mx/mde/expe" xmlns="http://palaciohierro.com.mx/mde/expe" xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="existencia-peticion" type="epType">
    <xs:annotation>
    <xs:documentation>Peticion de existencias para la Mesa de Eventos Web</xs:documentation>
    </xs:annotation>
    </xs:element>
    <xs:complexType name="epType">
    <xs:annotation>
    <xs:documentation>peticion de existencia</xs:documentation>
    </xs:annotation>
    <xs:sequence>
    <xs:element name="articulo" type="articuloType" maxOccurs="unbounded"/>
    </xs:sequence>
    </xs:complexType>
    <xs:complexType name="articuloType">
    <xs:annotation>
    <xs:documentation>articulo</xs:documentation>
    </xs:annotation>
    <xs:attribute name="id_articulo" type="IdentifierType" use="required"/>
    <xs:attribute name="sku" type="skuType" use="required"/>
    </xs:complexType>
    <xs:simpleType name="IdentifierType">
    <xs:annotation>
    <xs:documentation>identificador</xs:documentation>
    </xs:annotation>
    <xs:restriction base="xs:long">
    <xs:minInclusive value="0"/>
    <xs:maxInclusive value="999999999999999999"/>
    <xs:totalDigits value="22"/>
    <xs:fractionDigits value="0"/>
    </xs:restriction>
    </xs:simpleType>
    <xs:simpleType name="skuType">
    <xs:annotation>
    <xs:documentation>sku</xs:documentation>
    </xs:annotation>
    <xs:restriction base="xs:string">
    <xs:minLength value="11"/>
    <xs:maxLength value="20"/>
    <xs:pattern value="\d{11,20}"/>
    </xs:restriction>
    </xs:simpleType>
    </xs:schema>
    taking this sample XML file:
    <?xml version="1.0" encoding="UTF-8"?>
    <!--Sample XML file generated by XML Spy v4.4 U (http://www.xmlspy.com)-->
    <expe:existencia-peticion xmlns:expe="http://palaciohierro.com.mx/mde/expe" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://palaciohierro.com.mx/mde/expe
    C:\oracle\Oracle9iDS\jdev\mywork\testCompra\MesaEventos\src\ph\mesaeventos\schema\existencia-peticion.xsd">
    <articulo id_articulo="450" sku="12245110021"/>
    <articulo id_articulo="15" sku="45421213223"/>
    <articulo id_articulo="12" sku="121131231858"/>
    <articulo id_articulo="74" sku="4101031234545"/>
    <articulo id_articulo="871" sku="022324563212"/>
    </expe:existencia-peticion>
    with the following code:
    public Document getDOM( String existenciapeticionXML ) throws Exception
    // Obtain parser instance and parse the document
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating( true );
    factory.setNamespaceAware( true );
    DocumentBuilder builder = factory.newDocumentBuilder();
    byte buf[] = existenciapeticionXML.getBytes();
    ByteArrayInputStream stream = new ByteArrayInputStream( buf );
    Document doc = builder.parse( stream );
    return doc;
    I am getting the following Exception:
    oracle.xml.parser.v2.XMLParseException: Element 'expe:existencia-peticion' used but not declared.
    void oracle.xml.parser.v2.XMLError.flushErrors()
    XMLError.java:145
    void oracle.xml.parser.v2.NonValidatingParser.parseDocument()
    NonValidatingParser.java:263
    void oracle.xml.parser.v2.XMLParser.parse(org.xml.sax.InputSource)
    XMLParser.java:141
    org.w3c.dom.Document oracle.xml.jaxp.JXDocumentBuilder.parse(org.xml.sax.InputSource)
    JXDocumentBuilder.java:96
    org.w3c.dom.Document javax.xml.parsers.DocumentBuilder.parse(java.io.InputStream)
    DocumentBuilder.java:119
    org.w3c.dom.Document ph.mesaeventos.mesa.xml.ExistenciaPeticionDOM.getDOM(java.lang.String)
    ExistenciaPeticionDOM.java:26
    void ph.mesaeventos.mesa.xml.Test.main(java.lang.String[])
    Test.java:38
    What am I doing wrong? I am clueless... please help!
    Thanks,

    I finally managed to make it work.... well quite!
    Having an XML Doc like this:
    <?xml version="1.0"?>
    <existencia-peticion xmlns = "http://palaciohierro.com.mx/mde/expe">
    <articulo id_articulo="10" sku="00000000010"></articulo>
    <articulo id_articulo="11" sku="00000000011"></articulo>
    <articulo id_articulo="12" sku="00000000012"></articulo>
    <articulo id_articulo="13" sku="00000000013"></articulo>
    </existencia-peticion>
    with an schema like:
    <?xml version="1.0" encoding="UTF-8"?>
    <schema targetNamespace="http://palaciohierro.com.mx/mde/expe"
    xmlns="http://www.w3.org/2001/XMLSchema"
    xmlns:expe="http://palaciohierro.com.mx/mde/expe"
    elementFormDefault="qualified">
    <annotation>
    <documentation xml:lang="es">
    Esquema de peticion de existencias para la Mesa de Eventos Web
    Copyright 2002 palaciodehierro.com.mx. Todos los derechos reservados.
    </documentation>
    </annotation>
    <element name="existencia-peticion" type="expe:epType">
    <unique name="id_articulo">
    <selector xpath="expe:articulo"/>
    <field xpath="@id_articulo"/>
    </unique>
    <unique name="sku">
    <selector xpath="expe:articulo"/>
    <field xpath="@sku"/>
    </unique>
    </element>
    <complexType name="epType">
    <annotation>
    <documentation>peticion de existencias</documentation>
    </annotation>
    <sequence>
    <element name="articulo" type="expe:articuloType" maxOccurs="unbounded"/>
    </sequence>
    </complexType>
    <complexType name="articuloType">
    <annotation>
    <documentation>articulo</documentation>
    </annotation>
    <attribute name="id_articulo" type="expe:IdentifierType" use="required"/>
    <attribute name="sku" type="expe:skuType" use="required"/>
    </complexType>
    <simpleType name="IdentifierType">
    <annotation>
    <documentation>identificador</documentation>
    </annotation>
    <restriction base="long">
    <minInclusive value="0"/>
    <maxInclusive value="999999999999999999"/>
    <totalDigits value="18"/>
    <fractionDigits value="0"/>
    </restriction>
    </simpleType>
    <simpleType name="skuType">
    <annotation>
    <documentation>sku</documentation>
    </annotation>
    <restriction base="string">
    <minLength value="11"/>
    <maxLength value="20"/>
    <pattern value="\d{11,20}"/>
    </restriction>
    </simpleType>
    </schema>
    and with the following class:
    public class XMLValidator
    // Instancia singleton
    private static XMLValidator validator = new XMLValidator();
    * Constructor privado
    private XMLValidator()
    * Mitodo para acceder a la instancia Singleton de XMLValidator
    * @regresa <b>XMLValidator</b> La instancia de esta clase
    public static XMLValidator getValidator()
    return validator;
    public boolean validaEsquema( String docXML, String esquema ) throws Exception
    // Establece el URL correcto para el documento de esquema
    XSDBuilder builder = new XSDBuilder();
    URL url = createURL( esquema );
    // Construye el objecto del Schema XML
    try
    XMLSchema schemadoc = (XMLSchema)builder.build( url );
    // Valida el documento XML procesandolo contra el esquema
    return validate( docXML, schemadoc );
    catch( XMLParseException e )
    throw new Exception( "Error al analizar el documento XML: " + e.getMessage() );
    catch( Exception e )
    throw new Exception( "No es posible validar con el esquema: " + e.getMessage() );
    private static boolean validate(String docXML, XMLSchema schemadoc) throws Exception
    boolean isValid = false;
    // Crea un objeto Parser DOM de XML
    DOMParser dp = new DOMParser();
    // Establece el objeto Schema XML para la validacion
    dp.setXMLSchema( schemadoc );
    dp.setValidationMode( XMLParser.SCHEMA_VALIDATION );
    dp.setPreserveWhitespace( true );
    // Establece la salida de errores
    dp.setErrorStream( System.out );
    // Recupera los datos del documento XML en un objeto InputStream
    byte[] docbytes = docXML.getBytes();
    ByteArrayInputStream in = new ByteArrayInputStream( docbytes );
    // Parsea el documento y validalo contra el esquema
    try
    dp.parse( in );
    isValid = true;
    catch( Exception e )
    // Devuelve el documento XML DOM construido durante el parseo
    return isValid;
    I am able to validate when invoking with the XML and schemas in the parameters...
    Problem is that I have to include the attribute xmlns = "http://palaciohierro.com.mx/mde/expe" in my XML doc.
    What I really need is to be able to validate de XML doc against a stablished schema, when the XML doc does not include the
    xmlns attribute.

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

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

  • Dom importNode problem

    hi, i have problems with this code:
    public Document searchEngine(NodeList secNode){
         int i;
         Document newDoc=null;
         boolean trovato;
         try{
                   DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                   DocumentBuilder builder = factory.newDocumentBuilder();
                   newDoc = builder.newDocument();
                   Element root = newDoc.createElement("document");
                   newDoc.appendChild(root);
                   for (i=0 ; i<secNode.getLength(); i++){
                        trovato=search(secNode.item(i));
                        if (trovato) newDoc.importNode(secNode.item(i),true);
                   }                              f=false;
         }catch(Exception e){e.printStackTrace();}
         return newDoc;
    I have another method that writ retuner dom document to file, but my secNode that i try to import with ImportNode aren't present...
    btw i want an xml tree with:
    <document>
    imported node
    imported node
    </document>
    what's wrong?
    thanks, marco

    ok i understand the problem..
    importNode method work with apache xerces parser..

  • How to copy a node from one dom document to another?

    I have one dom document that I have to split up into multiple dom documents. I am able to get the inividual nodes that I want to put into seperate documents.
    My problem occurs when I create a new dom document and try to add the node from the parent document. I get an exception saying (copied from api: WRONG_DOCUMENT_ERR: Raised if newChild was created from a different document than the one that created this node. )
    How can I make it so that I can copy a node from one document and add it to another.

    Have you checked out the API called importNode in the DOM Document. It lets you move nodes between different documents.
    This api lets you simply copy the existing node from one document into another. without creating any new nodes for it.
    I have done a small example please have a look.
    Book.xml
    <?xml version="1.0"?>
    <books>
      <book>
        <name>Inside Corba</name>
      </book>
      <book>
        <name>Inside RMI</name>
      </book>
    </books>------------------------
    Book2.xml
    <?xml version="1.0"?>
    <books>
      <book>
        <name>Core Java </name>
      </book>
      <book>
        <name>Core JINI</name>
      </book>
    </books>-------------------
    MoveNode.java (copies nodes from doc2 into doc1)
    import java.io.*;
    import javax.xml.parsers.*;
    // structures
    import org.w3c.dom.*;
    import org.xml.sax.*;
    public class MoveNode
      public static void main(String[] args)
        // step1. create a factory and configure it
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        // step2. set various configurations
        factory.setValidating(false); // do not need validation at this time.
        factory.setIgnoringComments(false); // do not ignore comments
        factory.setIgnoringElementContentWhitespace(false); // do not ignore element content whitespace.
        factory.setCoalescing(false);
        factory.setExpandEntityReferences(true);
        // step 3 create a document builder
        DocumentBuilder builder = null;
        try
          builder = factory.newDocumentBuilder();
        catch(ParserConfigurationException e)
          e.printStackTrace();
        try
          Document doc1 = builder.parse(new File("book.xml"));
          Document doc2 = builder.parse(new File("book2.xml"));
          if (doc1 == null || doc2 == null)
            System.out.println("doc1 is null or doc2 is null");
            System.exit(1);
          } // if
          // fetch books from doc2
          NodeList list = doc2.getElementsByTagName("book");
          System.out.println("number of books found " + list.getLength());
          Node node1 = list.item(0);
          Node node2 = list.item(1);
          // get the root node of doc1
          Node root = (Node) doc1.getDocumentElement();
          root.appendChild(doc1.importNode(node1, false));
          root.appendChild(doc1.importNode(node2, false));
          //now doc1 should have 4 nodes
          System.out.println(doc1.getElementsByTagName("book").getLength());
        } // try
        catch(SAXException se)
          se.printStackTrace();
        catch(IOException ie)
          ie.printStackTrace();
    hope this helps.
    regards,
    Abhishek.

  • 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

  • From org.w3c.dom.Document to XML file

    Good morning to all! (morning here, in Barcelona).
    I have a problem and I don't know how to look for a solution (which google query to do, which class to study in the java api...).
    I parse a XML file into a Document with DOM, then make some modifications in its nodes... but how do I transform this modified information into a new XML file? is there any "toString" method for all the XML tree represented by the Document?
    thanks a lot!

    Output the DOM document with a Transformer
    TransformerFactory tFactory =
               TransformerFactory.newInstance();
                Transformer transformer = tFactory.newTransformer();
                DOMSource source = new DOMSource(document);
                StreamResult result = new StreamResult(new File("C:/output/output.xml"));
                transformer.transform(source, result);

  • Org.w3c.dom.Document not found

    I'm using jdk 1.6 and I'm getting "cannot find symbol" element when I try to compile to following simple code:
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import org.w3c.dom.Element;
    import org.w3c.dom.Document;
    import org.xml.sax.SAXException;
    public class TestXml {
        public static void main(String[] args) {
          DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
          DocumentBuilder builder = factory.newDocumentBuilder();
          Document = builder.newDocument();
          Element root = (Element) document.createElement("gene");
    }What do I need to get this to compile? I thought jaxp was built into jdk1.6, so why is it not being found?

    javac TestXml.java
    TestXml.java:14: cannot find symbol
    symbol  : variable Document
    location: class TestXml
          Document = builder.newDocument();
          ^
    TestXml.java:15: cannot find symbol
    symbol  : variable document
    location: class TestXml
          Element root = (Element) document.createElement("gene");
                                   ^
    2 errorsIn eclipse, the problem is shown as "Document cannot be resolved."

  • How to parse & update org.w3c.dom.Document

    Hi,
    I have a org.w3c.dom.Document "w3Doc" object which is converted to org.jdom.Document object using DOMBuilder().build(w3Doc) method.
    Now the problem which I'm facing is that this org.w3c.dom.Document object contains an illegal xml character & when DOMBuilder().build() method tries to create JDOM doc/tree from org.w3c.dom.Document it raises IllegalDataException & the application errors up.
    Now, I want to parse org.w3c.dom.Document "w3Doc" object & check for illegal xml character in the w3Doc & remove this character.
    Can anyone help me out in finding which parser should I use to read w3Doc & update the doc(by removing the illegal data).
    Thanks in advance,

    Normally a Document is the output of a parser, not the input to one. And all the parsers I know of will not allow invalid XML characters to pass. So it must be that you're creating Text nodes in your program that include invalid XML characters and adding them to a Document. (I'm surprised that the DOM implementation allows you to do that.)
    So you should just stop doing that, instead of trying to find something to clean up the mess after the fact. The XML Recommendation, in section 2.2, tells you what characters are valid in XML. You can find it here:
    http://www.w3.org/TR/REC-xml/

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

Maybe you are looking for

  • Down payment against Asset

    Dear Friends, we are using SAP ECC 6, Currently, there is no config, for Advance against Asset, we maintain below configuration ---  (Development Server)              Financial Accounting (New)                              Asset Accounting           

  • How to disable the Language dependent option for 0PROJECT and 0WBS_ELEMT

    Hi Friends,             Some Info Objects are re installed in latest version that's why DBW and QBW is not sinked. that's why giving transports errors.            In DBW both Info Objects(0PROJECT and 0WBS_ELEMT) having the option text language depen

  • HELP! Shuffle won't update songs

    I have been trying to update my shuffle song list but it won't let me. The shuffle recharges and plays ok but won't let me change the song list. I have uninstalled and restalled the IPod & Itunes but that doesn't fix it. Has any one else had this pro

  • Error mess when I try to export to PDF

    The file's security settings do not allow export.

  • Quicktime movies won't play on Apple Website

    I formatted my HD and reinstalled Snow Leopard. Last night and this morning I was watching the videos on http://www.apple.com/business/theater/#activecorners?sr=hotnews.rss, but tnight when I went back there, the movies won't play, nor will any other