DOM Document = null

I am trying to build a DOM document. The code I wrote (taken from examples) always returns a null.
There is no exception, everything seems OK but the document is null. It is unusable.
My JVM : 1.4.2-03-b02 on Windows
Same behavior on 1.4.2-08 on Linux
I can't manage to find my mistake.
Any clue ?
Thanks in advance
AF
Here is the code
package org.home.test.xerces;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
public class Builder {
     public static void main(String[] args) {
          Document xmlDoc=null;
          try {
          DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
          dbFactory.setValidating(false);
          dbFactory.setNamespaceAware(false);
          DocumentBuilder docBuilder = dbFactory.newDocumentBuilder();
          xmlDoc = docBuilder.parse(new File("E:\\arnold\\test.xml") );
          System.out.println("Document builder : " + docBuilder);
          System.out.println("Document implementation : " + xmlDoc.getImplementation());
          System.out.println("Document : " + xmlDoc);
          catch (Exception e) {
               System.out.println("Exception : " + e);
Result in the console is:
Document builder : org.apache.xerces.jaxp.DocumentBuilderImpl@1cb25f1
Document implementation : org.apache.xerces.dom.DOMImplementationImpl@e3b895
Document : [#document: null]

The returned Document isn't null. If it was, you'd just get "null" without the "[#document" part. Don't assume that a given implementation of Document will have a toString that spits back the XML.
Try printing out the doc's root element, or the names of the children.
You might also look into jdom. I know it has some prettyprint methods.

Similar Messages

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

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

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

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

    Anyone has any idea? Please help!!!
    xu

  • Create a DOM Document with DTD

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

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

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

  • Modifying a DOM document.

    i have a 100 MB file...where I am suppose to change a node value to null..
    i am using simple dom parser to achieve this task and it is working fine...
    but i need to pass
    -server -Xms 1G -Xmg 1G option to the java compiler and height is...it is taking 5 hours to complete updating the file.
    there are around 20000 records in my xml file.
    here is the code
    import java.io.File;
    import java.io.IOException;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.*;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.stream.StreamResult;
    import org.w3c.dom.Document;
    import org.w3c.dom.NodeList;
    import org.w3c.dom.Element;
    import org.xml.sax.SAXException;
    import org.xml.sax.SAXParseException;
    public class ChangeNodevalue {
         public static void main(String [] args) {
              Document document = null;
             DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
             factory.setValidating(false);
             factory.setNamespaceAware(false);
             try {
                  DocumentBuilder builder = factory.newDocumentBuilder();
                    document = builder.parse( new File("d:/samples/myprogs/valuechange.xml"));
                  replace(document, "PostalAddress", "CityNm");
                  DOMSource source = new DOMSource(document);
                // Prepare the output file
                 File file = new File("D:/samples/myprogs/valuechange1.xml");
                 StreamResult result = new StreamResult(file);
                 // Write the DOM document to the file
                 Transformer xformer = TransformerFactory.newInstance().newTransformer();
                 System.out.println("Wrote to new file");
                 xformer.transform(source, result);
             catch (SAXParseException spe) {
               spe.printStackTrace();
             catch (SAXException sxe) {
               sxe.printStackTrace();
             catch (ParserConfigurationException pce) {
               pce.printStackTrace();
             catch (IOException ioe) {
               ioe.printStackTrace();
            catch(TransformerConfigurationException tce) {
                 tce.printStackTrace();
            catch(TransformerException te) {
                 te.printStackTrace();
    public static void replace(Document doc, String tag, String sub_tag){ 
                Element child = null;
                NodeList matches = doc.getElementsByTagName(tag);
                for (int cd = 0; cd < matches.getLength(); cd++) {
                          Element tag1 = (Element)matches.item(cd);
                          NodeList children = tag1.getChildNodes();
                          for (int i = 0; i < children.getLength(); i++) {
                                 if ((children.item(i)).getNodeName().equals(sub_tag)) {
                                 System.out.println((children.item(i)).getNodeName());
                                 child = (Element)children.item(i);
                                 if (child != null) {
                                          System.out.println(child.getFirstChild().getNodeValue());
                                     child.getFirstChild().setNodeValue("");
    }will use of JAXP / some other parser will do any good....any inputs???
    thank you..
    chintan.

    I don't believe the Xerces parser can be configured to leave entity references as is if the entity reference is located in an attribute value. I think you might have more luck if the entity reference is inside an element.

  • Reading DOM document text nodes

    I have created a DOM document from a text string, which seems fine. The structure is something like:
    <BOOK>
        <BOOK_ID>1</BOOK_ID>
        <BOOK_NAME>Test Book 1</BOOK_NAME>
        <BOOK_DESC>This is a test book</BOOK_DESC>
    </BOOK>When I try to traverse this structure using DOM, for each node (BOOK_ID, BOOK_NAME, BOOK_DESC), I get two nodes - one ElementNode, one TextNode, as I would expect.
    However, when I call get value on the TextNodes, it simply returns "\n ", instead of returning the text between the tags.
    Does any one know why?
    Thanks a lot,
    Jim

    I have some thing similar probelm but failed to get this working. Which ever nodes I try, all I get is node value "null" and say's that the node type is ELEMENT_NODE, but that node is TEXT_NODE as per schema.
    So I tried to validate the schema xml file which is external (even the xml file is located external), but failed to get this working too, now just stranded wihtout any clues what I have to do.
    I am using DOM parser with j2sdk-1.4.1_05.
    My xml file is:
    <?xml version="1.0" standalone="yes" ?>
    <IRXML CorpMasterID="9999999">
    <NewsRelease ReleaseID="215555" DLU="20020814 15:43:00" ArchiveStatus="Current">
    <Title>Viking Energy CEO and CFO Certify Financial Reports for SEC</Title>
    <Date Date="20020814" Time="15:32:00">8/14/2002 3:32:00 PM</Date>
    <Categories>
    <Category>Financial Releases</Category>
    </Categories>
    </NewsRelease>
    </IRXML>
    The nodes <Title> and <Date> are text nodes, so any help is appreciated.
    Thanks.

  • Security Exception in trying to get a org.w3c.dom.Document

    Hi,
    I'm trying to get an org.w3c.dom.Document using the following code----
         String configFileName = "discoveryconsts.xml";
              DocumentBuilder db = null;
              Document xmlDocument = null;
              DocumentBuilderFactory dbf = null;
         dbf = DocumentBuilderFactory.newInstance();
    System.out.println("The DocumentBuilderFactory is :" + dbf);     
    //the exception happens here,while building the DocumentBuilder.
         db = dbf.newDocumentBuilder();
    System.out.println("The DocumentBuilder is :" + db);          try
         xmlDocument = db.parse(configFileName);
    System.out.println("The Document Builder is :" + db);
    catch(Exception e)
         System.out.println("The Exception is :"+ e);
    System.out.println("The XML Document is :" + xmlDocument);
    The error obtained is in the ---
    java.lang.SecurityException: sealing violation
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:234)
    at java.net.URLClassLoader.access$100(URLClassLoader.java:56)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:195)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:297)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:286)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:253)
    at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:313)
    at org.apache.xerces.jaxp.DocumentBuilderImpl.<init>(DocumentBuilderImpl.java:98)
    atorg.apache.xerces.jaxp.DocumentBuilderFactoryImpl.newDocumentBuilder(DocumentBuilderFactoryImpl.java:87)
    at Prototype.ChangingDiscConstsFile.discoveryConstants(ChangingDiscConstsFile.java:36)
    at Prototype.ChangingDiscConstsFile.main(ChangingDiscConstsFile.java:74)
    This error is obtained at runtime(ie.The file gets compiled).
    Kindly let me know the reason for the exception.
    regards,
    Karan.

    Hello Satya,
    Have you checked if the cross domain security between the domain WLS 10.3.5 and the backend server is enabled?
    Trust between domains is established so that principals in a Subject from one WebLogic domain can make calls in another domain. In previous releases of WebLogic Server, there was only one type of domain trust that is now referred to as Global Trust. WebLogic Server now supports a type of domain trust that is referred to as Cross Domain Security. The following sections explain how to configure each domain trust type:
    Enabling Cross Domain Security Between WebLogic Server Domains
    Enabling Global Trust
    http://docs.oracle.com/cd/E21764_01/web.1111/e13707/domain.htm#i1176046

  • WebEngine goes in State SUCCEEDED but DOM in null

    I'm trying to develop a JavaFX web page loader. I want to explore the DOM tree after page loading, so I load the DOM after I receive a Worker State SUCCEEDED, but the problem in that when I test my code on the url: www.repubblica.it, I got SUCCEEDED but the DOM is still null.
    It seems to be that the page is not completely loaded although I got the SUCCEEDED event.
    This is the peace of code that fails:
    webEngine.getLoadWorker().stateProperty().addListener(new ChangeListener<Worker.State>() {
         @Override
         public void changed(ObservableValue ov, Worker.State oldState, Worker.State newState) {
    if (newState == Worker.State.SUCCEEDED) {
    webEngine.getDocument(); // On www.repubblica.it dom is still null
    I also tried to reload the page when the DOM is null and it seems to work but completely random (sometimes I have to reload two times, sometimes three and so on).
    This problem is driving me crazy. Any help wiill be greatly appreciated!
    Thanks in advance.

    I see an exception occurring there which likely ruins the document. Filed as https://javafx-jira.kenai.com/browse/RT-30835

  • Org.w3c.dom Document newbie question

    hello
    I have a string of an XML document that i want to make into a dom.Document. i can't seem to create it though.
    DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    org.w3c.dom.Document doc =  db.parse(new StringBufferInputStream(s.substring(s.indexOf("?>") + 2).trim()));the String s has a xml header with <? and ?> and you see here i am stripping that off the top... i tried with it on, and w/o, but i keep getting back a Document that is null. what is required for a document to be made? can't i just do <sometag>blah</sometag>
    and thats good enough?

    getting back a Document that is nullIf that means that the variable doc contains a null reference after you execute that statement, then most likely the statement is throwing an exception that you are ignoring. And that exception is probably because you're passing malformed XML to the parser... you have done some debugging to see what string you are passing to it, haven't you?
    And why StringBufferInputStream? The whole class is deprecated. Better to use a StringReader instead:doc = db.parse(new InputSource(new StringReader(...)));(This is posted frequently on this forum but here it is yet again.)

  • Org.w3c.dom.Document.getElementById() not working for me

    I am having trouble using the .getelementById for the org.w3c.dom.Document class. I have devised a workaround, but was wondering what I have been doing wrong in the first place.
    My XML file contains, in part, a bunch of "sections" as outlined below:
    <section id="uniqueString">
       <icon ... />
       <window ... />
    </section>I want to get a "section" whose ID is String s . I tried using .getElementById()
    // document is of class org.w3c.dom.Document, and has parsed in an XML file
    // String s = "uniqueString"
    Element e = document.getElementById(s);However, e is null every time I run this. I have tried it with different Strings which look for other XML tags, but it always is null . I have devised a workaround:
    NodeList sections = document.getElementsByTagName("section");
    for (int i = 0; i < sections.getLength(); ++i) {
         if (((Element) sections.item(i)).getAttribute("id").equals(s)) {
              e = (Element) sections.item(i);
    // Do something with eSo the functionality I need is there; however, I was just wondering if anybody sees what I'm doing wrong in the attempt to use getElementById(). It's not essential that I find out, however it would improve my program's readability, probably improve the efficiency, and help me understand whatever concept I seem to be missing. I have been all through the javadoc online and I can't seem to figure out what's up with it.

    This is a user error. If it is any consolation, it is not uncommon.
    By "Id" this method looks for the attribute defined in the schema for this kind of XML file as an ID. It may or may not be "id".
    The JavaDoc for this method says:
    Attributes with the name "ID" or "id" are not of type ID unless so defined.
    So, you could have an attribute "programnum" defined as an ID in the schema, and find a value of that attribute with the getElementById() method.
    Dave Patterson

  • Org.w3c.dom.Document toString() ?

    hi i have a constructed org.w3c.dom.Document var newDoc...
    in ibm developerworks tutorial there is a line newDoc.toString() but that gives "[#document null]"
    newDoc.getDocumentElement().getNodeValue() gives the xml string in jdk 1.4 but not in jdk 1.3 wih apache xerces 2.6.2
    how to i get the xml in string output? (i do not wish to use sun java web service development platform)
    please email responses to vishalrao at gmail dot com , thanks!

    From what I saw there was no change and the document getNodeValue always returns null in jdk1.4 as well.
    you can use the transform api to serialize xml into any serialized output form, including strings.
    look into http://java.sun.com/j2se/1.4.2/docs/api/javax/xml/transform/Transformer.html

  • How to add node value using org.w3c.dom.Document?

    Hi ,
    I'm using org.w3c.dom.Document to deal with xml files. I could successfully add nodes , and their attributes. However I could not add a value of the node. (e.g. <myNode>I couldn't add this value</myNode>)
    does anyone know how to deal with this?
    I tried subNode.setNodeValue("the value i can't add"); whereas the subNode is an instance of org.w3c.dom.Node... i know this is interface i of course used the concrete class
    org.apache.crimson.tree.ElementNode
    but when I used the subNode.getNodeValue() i simply got null?
    can u plz help me?
    thanks in advance

    Reading the API documentation for the Node interface might help. At least you wouldn't be surprised when the results are exactly what the documentation says they will be.
    What would really help would be forgetting the idea that an Element can have a value. Text nodes have values, though, so create a Text node and make it the child of the Element node.

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

Maybe you are looking for

  • Oddball WCS map issue !? help please

    Hi, have tried to create a perimeter on WCS map editor as a test to keep some of the assets from appearing way off the map. It made no real difference. Problem is to remove the perimeter I selected new perimeter (which erases last perimeter) and save

  • Why do embeded presentations from Prezi no longer work?

    Embeded interactive presentations from Prezi no longer work, when viewed on Firefox. They still work fine, when viewed on Google. This is a problem whether I am signed on or not.

  • Someone is sending texts from a different phone

    How do I stop someone from sending texts from my number?  They've hacked my account. I even changed mu number and said person found me again. Help!

  • Howto? XMLSchema validation on abstract/substitutionGroup and complexType

    Hi, I'm following the examples on [http://download.oracle.com/docs/cd/B10501_01/appdev.920/a96621/adx06scj.htm|http://download.oracle.com/docs/cd/B10501_01/appdev.920/a96621/adx06scj.htm] . A little change and it worked for me. I wanted to try out a

  • Time Machine Preferences breaks when I wake from sleep

    I have recently started having a problem. When I start my computer, everything is functioning fine. I am able launch System Preferences and open any preference pane and quit System Preferences and everything is fine. When I put my computer to sleep a