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.

Similar Messages

  • Org.w3c.dom.Document -- text

    Hello.
    I have parsed org.w3c.dom.Document.
    Is here a library that can print it to a xml file?
    Secondly I wish print it as .html, so output should a bit differ from standard .xml output.

    Yes. In both cases you use a Transformer. (That's in package javax.xml.transform.) You get it via one of the TransformerFactory.newTransformer() methods. To do a straight copy you use the method with no parameters, which does an "identity transformation". To transform to HTML, you use the method with an XSLT for its parameter.

  • Read number of XML nodes in a document& return result in text member

    Hi all,
    I wonder if you can help me with the following:
    I want to read the number of nodes in an XML document and
    return the result in a text cast member. This is what i am doing so
    far, but it refuses to work

    Hi Sean
    This is the handler i created based on your suggestions.
    Although it is working perfectly for some reson it creates one
    extra end tag at the end of the xml file. Is there any way to fix
    this?
    global whichxml
    on XMLscript2
    GrQuestion = member("Gr_Questions").text
    EnQuestion = member("questions_stage").text
    re3 = "("&EnQuestion&")"
    re4 = "(8859-1)"
    global gFileIO
    gFileIO = new(xtra "FileIO")
    gFileIO =new (xtra "FileIO")
    gFileIO.createFile("xml\"&whichxml&"" & ".xml")
    gFileIO.openFile(the moviePath &
    "xml\"&whichxml&"" & ".xml" , 0)
    tXMLStr = gFileIO.readFile()
    tXMLStr2= RegExp_Replace(tXMLStr, re4, "8859-7", "gi")
    tXMLStr2= RegExp_Replace(tXMLStr2, re3,
    ""&GrQuestion&"", "gi") --replace with greek text
    positiona= offset(re4,tXMLStr) --find the position of the
    first character
    setPosition(gFileIO,positiona)
    writeString(gFileIO,tXMLStr2) --write the new string
    gFileIO.closeFile()
    gFileIO = VOID
    end

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

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

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

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

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

  • Read an XML file with java: Document to Node conversion

    Hello,
    I want to read an XML file and convert data into a Node instance because I need this for an XForm application.
    My code is:
    private Node workstationType;
    public Node initModel() {
    try {
    //This one will hold the results
    Document document;
    //loading from XML File
    String fileName="C:\\documents\\iniForm.xml";
    FileInputStream inXML = new FileInputStream(fileName);
    BufferedReader in = new BufferedReader(new InputStreamReader(inXML));
    document = XMLLoader.loadFromStream(in);
    } catch (Exception e) {
    System.err.println("ERROR:" + e.getMessage());
    e.printStackTrace(System.err);
    //Create the node for the root, 'typeOfWorkstation'
    workstationType = document.getDocumentElement(); //A
    //Return the root node
    return (workstationType);
    The problem: I can convert Node instance to Document instance (line A)
    The error message is: "document cannot be resolved".
    How can I do that??
    Thank you
    Sylvain

    Here is my XMLLoader class:
    public class XMLLoader {
         public static Document loadFromStream(Reader reader) throws Exception {
              //Build a DOM document with the reader
              //prepare DOM document
              DOMImplementation impl;
              DocumentBuilder builder;
              try {
                   // Find the implementation
                   DocumentBuilderFactory factory =
                        DocumentBuilderFactory.newInstance();
                   factory.setNamespaceAware(false);
                   factory.setValidating(false);
                   builder = factory.newDocumentBuilder();
                   impl = builder.getDOMImplementation();
                   //Read and parse the XML input stream into a DOM document
                   Document document = builder.parse(new InputSource(reader));
                   return document;
              } catch (IOException ex) {
                   throw new RuntimeException(
                        "[XMLLoader.loadFromFile]: Failed loading the InputStream. Root cause: \n"
                             + ex);
              } catch (Exception ex) {
                   throw new RuntimeException(
                        "[XMLLoader.loadFromFile]: Failed to initialize DOM factory. Root cause: \n"
                             + ex);

  • 'Edit Document Text' in Adobe Reader XI

    There is 'Edit document text' in Acrobat Pro X to get the properties of the text like font name, size.   Does Adobe Reader XI has this option. If not, how can we get the text properties in Reader XI.

    Not available in Adobe Reader.

  • #text nodes

    Hello,
    I am parsing xml document using xerces with schema validation on, without DTD.
    <xs:element name="variant">
    <xs:complexType>
    <xs:sequence>
    <xs:element ref="ds:default"/>
    <xs:element ref="ts:answer"/>
    </xs:sequence>
    </xs:complexType>
    </xs:element>
    As I understand this element should be "element only": without #text nodes in the dom tree.
    But I get: #text default #text answer #text.
    Can I fix it?
    Thanks
    Justinas

    Do you have white space between the nodes? I believe you can tell the parser to ignore white space that is not required by the schema.

  • CDATA sections converted to text nodes by XMLDOM parser

    I have done a lot of reading, experimentation and openned a TAR on this. I am suprised nobody else has posted on the issue. The xmlparser.parseClob call appears to parse an XML document properly but converts CDATA sections into text nodes.
    For example take the following XML:
    <some><pnode><![CDATA[the <xml>]]></pnode></some>
    If I immediately write it back out using xmldom.writeToClob the resulting XML will be:
    <some>
    <pnode>the &amp;#60;xml></pnode>
    </some>
    For one I wish writeToClob wouldn't add whitespace (but that's another issue), but as you can see the CDATA node no longer exists, being replaced by an encoded text node.
    I wrote code to traverse the DOM outputting node types and even writing a similar printer to the writeToClob. The fact is there really is no CDATA node in the DOM after parsing. Instead the code which traverses the DOM identifies a single text node with CDATA text contained in it.
    In my opinion this is extremely odd default behavior and I cannot seem to work around it due to the fact that the DOM structure is not created properly by the parse. Please tell me that other people have ran into this behavior and I'm not just nuts? Better yet, please just tell me I'm doing something wrong and you have the answer...that would be kinder to my project schedule.
    If you like I have example code. I am using the xmldom API on Oracle 9.2.0.4.

    Thanks for the response Mark. I have gotten some feedback from my TAR as well. We are using version 9.2.0.*. I have since learned that this is a bug in the xmldom implementation based on Java. It has been recommended that I use the dbms_* packages as you suggested. I originally attempted to use the dbms_* packages (the C-based implementation) when following the tutorials and other documentation but for some reason we do not seem to have those packages installed. I was directed by my DBA's to use the other package as we both bevelieved it was just the same package in a different location. I am working with my DBA to get the C-based dbms_* packages installed.

  • Removing ignorable whitespace from DOM document

    Dear all,
    I am trying to read in an XML document that contains a lot of ignorable whitespace between elements. I am using the DOM model to parse and read in the file. Is there an easy way to tell the parser to ignore all ignorable whitespace characters in text nodes? Or do I have to write a routine to pre-process the DOM document?
    (xml:space="default" is set in the root element)
    Thanks a lot in advance!
    Netwundi

    I agree DrClap with your assertion. However, having read normalize(), it does seem quirky. According to the Javadocs for Node:
    public void normalize()
    Puts all Text nodes in the full depth of the sub-tree underneath this Node, including attribute nodes, into a "normal" form where only structure (e.g., elements, comments, processing instructions, CDATA sections, and entity references) separates Text nodes, i.e., there are neither adjacent Text nodes nor empty Text nodes. This can be used to ensure that the DOM view of a document is the same as if it were saved and re-loaded, and is useful when operations (such as XPointer lookups) that depend on a particular document tree structure are to be used.In cases where the document contains CDATASections, the normalize operation alone may not be sufficient, since XPointers do not differentiate between Text nodes and CDATASection nodes.- Saish

  • 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 create org.w3c.dom.Document.

    Hi,
    I have my complete xml file in a String variable like
    String strXml = " <?xml version="1.0"?>
    <report>
    <name>testReport & report
    <duration>Jan to Feb</duration>
    <reportId>1</reportId>
    </report> "
    I need to create a "org.w3c.dom.Document" object from the above "strXml" variable.
    Thanks in advance for your answers,
    Sha S.

    this is the code snippet that would answer u r question
    import org.apache.xml.serialize.XMLSerializer;
    import org.w3c.dom.Attr;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.NamedNodeMap;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import org.w3c.dom.Text;
    import org.w3c.dom.ProcessingInstruction;
    import org.xml.sax.InputSource;
    import com.exel.businessobjects.*;
    StringReader srxml = new StringReader(xmlcontent);
    Reader rxml     = (Reader)srxml;
    InputSource isxml = new InputSource(rxml);
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(isxml);

  • Extra #Text node

    Hi,
    It seems I got extra #Text node in my DOM object. For example, if my XML is as follows:
    <Root>
    <FirstElement>Value</FirstElement>
    </Root>
    My DOM tree will look like:
    + ELEMENT: Root
    + #TEXT:
    + ELEMENT: FirstElement
    + #TEXT: Value
    + #TEXT:
    Is there a way to avoid those extra empty #Text Node?

    //Create a DocumentBuilderFactory 
    DocumentBuilderFactory factory =
                DocumentBuilderFactory.newInstance();
    //Set the factory object to be validating
    factory.setValidating(true);
    //Set the factory object to not parse empty text nodes
    factory.setIgnoringElementContentWhitespace(true);
    //Create a DocumentBuilder and parse XML document
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document     document = builder.parse(new File("input.xml"));

  • XPath text() node comparison

    I have an XML document that looks something like:
    <A>
    <B>One
    </B>
    <B>Two
    </B>
    <B>Three
    </B>
    </A>
    I am using XPathAPI to evaluate my XPath Expressions and I would like to write an expression that will select a node of type B based on the value of its text node. I looked around for some examples at how to compare a text node but I couldn't find any. I thought it would be something like "//B[@text()='Two']" (or something similar) but nothing I have tried has worked. Can anyone offer some advice?
    Thanks in advance,
    Matt

    I think you're close. But the "@" in your expression is shorthand for the attribute axis, for example "@text" would be looking for an attribute named text. Try this instead:
    //B[text()='Two']
    Also beware of whitespace; your example has a B element whose text node contains 'Two' followed by a newline character, and the example above won't match that. To get rid of surplus whitespace, use the normalize-space function (I think that's it, check your reference):
    //B[normalize-space(text())='Two']

Maybe you are looking for