?
Solved

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

Posted on 2005-05-16
20
Medium Priority
?
486 Views
Last Modified: 2013-11-23
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>
0
Comment
Question by:yuxie
  • 11
  • 9
20 Comments
 
LVL 35

Expert Comment

by:TimYates
ID: 14010379
0
 

Author Comment

by:yuxie
ID: 14010591
...
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
 
LVL 35

Expert Comment

by:TimYates
ID: 14010615
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
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 

Author Comment

by:yuxie
ID: 14010757
Yes, my program have the import org.w3c.dom.*;

are there any way to replace this argument: "Element dictionary = (Element)Word.getParentNode();"?
0
 
LVL 35

Expert Comment

by:TimYates
ID: 14010767
what version of Java are you using?
0
 

Author Comment

by:yuxie
ID: 14010823
how can know my version?

i am using the j2sdk1.4.2_03
0
 
LVL 35

Expert Comment

by:TimYates
ID: 14010891
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
 
LVL 35

Expert Comment

by:TimYates
ID: 14010896
As you can see, it writes it out to dictionary_new.xml

:-)
0
 
LVL 35

Accepted Solution

by:
TimYates earned 1000 total points
ID: 14010987
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
 

Author Comment

by:yuxie
ID: 14011070
hey... hey... your program is worked.

but why mine cannot... let me try again and again
0
 
LVL 35

Expert Comment

by:TimYates
ID: 14011122
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
 
LVL 35

Expert Comment

by:TimYates
ID: 14011496
Did you get yours working then?

Cool :-)

Good luck with it all!

Tim
0
 

Author Comment

by:yuxie
ID: 14011565
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
 
LVL 35

Expert Comment

by:TimYates
ID: 14011584
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
 

Author Comment

by:yuxie
ID: 14011797
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
 
LVL 35

Expert Comment

by:TimYates
ID: 14012409
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
 

Author Comment

by:yuxie
ID: 14012607
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
 
LVL 35

Expert Comment

by:TimYates
ID: 14016872
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
 

Author Comment

by:yuxie
ID: 14030030
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
 

Author Comment

by:yuxie
ID: 14037235
where r u ? dear Tim... i need ur help!
0

Featured Post

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

What do responsible coders do? They don't take detrimental shortcuts. They do take reasonable security precautions, create important automation, implement sufficient logging, fix things they break, and care about users.
This article will show how Aten was able to supply easy management and control for Artear's video walls and wide range display configurations of their newsroom.
Video by: Mark
This lesson goes over how to construct ordered and unordered lists and how to create hyperlinks.
Six Sigma Control Plans
Suggested Courses
Course of the Month13 days, 22 hours left to enroll

809 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question