DOM: how to use JAVA to add a element in xml fragment?

Hi experts,

how to add a <summary></summary> in the xml fragement

xml file:
<dictionary>
  <word>...</word>
  <word>...</word>
</dictionary>

now i wanna add a <summary> inside the <dictionary>, like:
<dictionary>
  <word>...</word>
  <word>...</word>
  <summary>...</summary>
</dictionary>
yuxieAsked:
Who is Participating?
 
TimYatesConnect With a Mentor Commented:
This is probably better (as it only adds one summary, and it prints out the words in the dictionary) :

import java.io.* ;
import javax.xml.parsers.* ;
import javax.xml.transform.* ;
import javax.xml.transform.dom.* ;
import javax.xml.transform.stream.* ;

import org.w3c.dom.* ;
import org.xml.sax.* ;

public class BasicDom
{
  public static void main( String[] args )
  {
    Document doc = parseXmlFile( "dictionary.xml", false ) ;
    try
    {
      // Prepare the DOM document for writing
      Source source = new DOMSource( doc ) ;

      // Prepare the output file
      File file = new File( "dictionary_new.xml" ) ;
      Result result = new StreamResult( file ) ;

      // Write the DOM document to the file
      Transformer xformer = TransformerFactory.newInstance().newTransformer() ;
      xformer.transform( source, result ) ;
    }
    catch( TransformerConfigurationException e )
    {
    }
    catch( TransformerException e )
    {
    }

  }

  // Parses an XML file and returns a DOM document.
  // If validating is true, the contents is validated against the DTD
  // specified in the file.
  public static Document parseXmlFile( String filename, boolean validating )
  {
    try
    {
      // Create a builder factory
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance() ;
      factory.setValidating( validating ) ;

      // Create the builder and parse the file
      Document doc = factory.newDocumentBuilder().parse( new File( filename ) ) ;

      NodeList words = doc.getElementsByTagName( "word" );

      Node firstWord = null ;
      for( int i = 0 ; i < words.getLength() ; i++ )
      {
        Node wordNode = words.item( i );
        if( firstWord == null )
          firstWord = wordNode ;
        Element word = (Element)wordNode;
        System.out.println( "Found word node : " + word.getChildNodes().item( 0 ) ) ;
      }

      Element summary = doc.createElement( "summary" );
      Text summaryContent = doc.createTextNode( "I am a summary!" ) ;
      firstWord.getParentNode().appendChild( summary ) ;
      summary.appendChild( summaryContent ) ;
      return doc ;
    }
    catch( SAXException e )
    {
      // A parsing error occurred; the xml input is not valid
    }
    catch( ParserConfigurationException e )
    {
    }
    catch( IOException e )
    {
    }
    return null ;
  }
}

And it puts text in the summary...

I have dictionary.xml as:

<dictionary>
  <word>tim</word>
  <word>yates</word>
</dictionary>

and it spits out dictionary_new.xml as

<dictionary>
  <word>tim</word>
  <word>yates</word>
<summary>I am a summary!</summary></dictionary>

and prints out:

Found word node : tim
Found word node : yates

Tim.
0
 
yuxieAuthor Commented:
...
Document doc = builder.parse("dictionary.xml");
NodeList Words = doc.getElementByTagName("word");

Node WordNode = Words.item(i);
Element Word = (Element)WordNode;

Element dictionary = (Element)Word.getParentNode();
Element Summary = doc.createElement("summary");
dictionary.insertBefore(Summary,dictionary.getLastChild().getNextSibling());
...

buy when i compile this, the system showed:
   "cannot resolve symbol
    symbol : variable Word
    Element dictionary = (Element) Word.getParentNode();"
                                                  ^
what's wrong in my code?
0
Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
TimYatesCommented:
Do you have

import org.w3c.dom.* ;

or

import org.w3c.dom.Element ;

in your java file?  That's the "Element" this refers to :-)


0
 
yuxieAuthor Commented:
Yes, my program have the import org.w3c.dom.*;

are there any way to replace this argument: "Element dictionary = (Element)Word.getParentNode();"?
0
 
TimYatesCommented:
what version of Java are you using?
0
 
yuxieAuthor Commented:
how can know my version?

i am using the j2sdk1.4.2_03
0
 
TimYatesCommented:
Strange...  the "Element" class should exist...

Right...I had a go...  I took code from those 3 links, and got:

----------------------------------BasicDom.java

import java.io.* ;
import javax.xml.parsers.* ;
import javax.xml.transform.* ;
import javax.xml.transform.dom.* ;
import javax.xml.transform.stream.* ;

import org.w3c.dom.* ;
import org.xml.sax.* ;

public class BasicDom
{
  public static void main( String[] args )
  {
    Document doc = parseXmlFile( "dictionary.xml", false ) ;
    try
    {
      // Prepare the DOM document for writing
      Source source = new DOMSource( doc ) ;

      // Prepare the output file
      File file = new File( "dictionary_new.xml" ) ;
      Result result = new StreamResult( file ) ;

      // Write the DOM document to the file
      Transformer xformer = TransformerFactory.newInstance().newTransformer() ;
      xformer.transform( source, result ) ;
    }
    catch( TransformerConfigurationException e )
    {
    }
    catch( TransformerException e )
    {
    }

  }

  // Parses an XML file and returns a DOM document.
  // If validating is true, the contents is validated against the DTD
  // specified in the file.
  public static Document parseXmlFile( String filename, boolean validating )
  {
    try
    {
      // Create a builder factory
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance() ;
      factory.setValidating( validating ) ;

      // Create the builder and parse the file
      Document doc = factory.newDocumentBuilder().parse( new File( filename ) ) ;

      NodeList words = doc.getElementsByTagName( "word" );

      for( int i = 0 ; i < words.getLength() ; i++ )
      {
        Node wordNode = words.item(i);
        Element word = (Element)wordNode;

        Element dictionary = (Element)word.getParentNode();
        Element Summary = doc.createElement("summary");
        dictionary.insertBefore(Summary,dictionary.getLastChild().getNextSibling());
      }
      return doc ;
    }
    catch( SAXException e )
    {
      // A parsing error occurred; the xml input is not valid
    }
    catch( ParserConfigurationException e )
    {
    }
    catch( IOException e )
    {
    }
    return null ;
  }
}

0
 
TimYatesCommented:
As you can see, it writes it out to dictionary_new.xml

:-)
0
 
yuxieAuthor Commented:
hey... hey... your program is worked.

but why mine cannot... let me try again and again
0
 
TimYatesCommented:
If you get stuck, post your non-working program here, and I can have a look at it :-)

We'll sort it out, now we know how to do it :-)

Tim
0
 
TimYatesCommented:
Did you get yours working then?

Cool :-)

Good luck with it all!

Tim
0
 
yuxieAuthor Commented:
wo... your are so great. my program is ok now... it can add the summary element already..

now i have to add the attributes in the summary... and have to do some search... maybe will ask you again if i have any problems.

thank you so so so much!
0
 
TimYatesCommented:
No problems :-)  Glad I could help :-)

Good luck with it all :-)

Tim

PS:  The java area of this site:  http://www.experts-exchange.com/Programming/Programming_Languages/Java/  will probably get you more people jumping in to help :-)
0
 
yuxieAuthor Commented:
Hi Tim,

if i wanna get the <word>'s child node , can i juse the getChildNode()?

but if like that
<word>
  <de>...</de>
  <sn>...</sn>
</word>

Element child = word.getChildNode();
child = <de> or <sn>?
0
 
TimYatesCommented:
I *think* it will be <de> in that case...

But you will probably need to get all the childNodes as a NodeList, and look at them one at a time to be sure...

Tim
0
 
yuxieAuthor Commented:
wo... i wanna calculate the number of  <word>node that has the <de> element, but after tried many ways , it still be non-work.

my assignment is so difficult for me... now so headache.. i will go to sleep now.. because i am in Australia, now is 4am laaa.
0
 
TimYatesCommented:
Ok, I have a dictionary.xml file like this:

<dictionary>
  <word>
    <de>allen</de>
    <sn>something</sn>
  </word>
  <word>
    <fr>aller</fr>
    <de>strasse</de>
    <sn>feet</sn>
  </word>
  <word>
    <sn>tim</sn>
    <te>fish</te>
  </word>
</dictionary>

and this is my code:

import java.io.* ;
import javax.xml.parsers.* ;
import javax.xml.transform.* ;
import javax.xml.transform.dom.* ;
import javax.xml.transform.stream.* ;

import org.w3c.dom.* ;
import org.xml.sax.* ;

public class BasicDom
{
  public static void main( String[] args )
  {
    Document doc = parseXmlFile( "dictionary.xml", false ) ;
    try
    {
      // Prepare the DOM document for writing
      Source source = new DOMSource( doc ) ;

      // Prepare the output file
      File file = new File( "dictionary_new.xml" ) ;
      Result result = new StreamResult( file ) ;

      // Write the DOM document to the file
      Transformer xformer = TransformerFactory.newInstance().newTransformer() ;
      xformer.transform( source, result ) ;
    }
    catch( TransformerConfigurationException e )
    {
    }
    catch( TransformerException e )
    {
    }

  }

  // Parses an XML file and returns a DOM document.
  // If validating is true, the contents is validated against the DTD
  // specified in the file.
  public static Document parseXmlFile( String filename, boolean validating )
  {
    try
    {
      // Create a builder factory
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance() ;
      factory.setValidating( validating ) ;

      // Create the builder and parse the file
      Document doc = factory.newDocumentBuilder().parse( new File( filename ) ) ;

      NodeList words = doc.getElementsByTagName( "word" );

      Node firstWord = null ;
      for( int i = 0 ; i < words.getLength() ; i++ )
      {
        Node wordNode = words.item( i );
        if( firstWord == null )
          firstWord = wordNode ;
        // ok, we have a word node.  Scan it for <de> nodes...
        NodeList list = wordNode.getChildNodes() ;
        for( int j = 0 ; j < list.getLength() ; j++ )
        {
          Node wordChild = list.item( j ) ;
          if( wordChild.getNodeName().equals( "de" ) )
          {
            // get the contents of this <de> tag
            String deCont = wordChild.getFirstChild().getNodeValue() ;
            System.out.println( "Word node #" + i + " contains a <de> tag containing '" + deCont + "'" ) ;
          }
        }
      }

      Element summary = doc.createElement( "summary" );
      Text summaryContent = doc.createTextNode( "I am a summary!" ) ;
      firstWord.getParentNode().appendChild( summary ) ;
      summary.appendChild( summaryContent ) ;
      return doc ;
    }
    catch( SAXException e )
    {
      // A parsing error occurred; the xml input is not valid
    }
    catch( ParserConfigurationException e )
    {
    }
    catch( IOException e )
    {
    }
    return null ;
  }
}

and I get this result:

Word node #0 contains a <de> tag containing 'allen'
Word node #1 contains a <de> tag containing 'strasse'

Tim
0
 
yuxieAuthor Commented:
now i am gonna do a SAX  using java to do a same function of above  DOM program. please give some hints, i totally not too understand the SAX.

i will ask this same question again in the new topic with points ... i will there is better to let u get the point.
0
 
yuxieAuthor Commented:
where r u ? dear Tim... i need ur help!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.