Biblioteca Java - Blame information for rev 3

Subversion Repositories:
Rev:
Rev Author Line No. Line
3 mihai 1 /*
2  * Citeste un fisier XML folosind DOM
3  * TestDOM.java
4  */
5 package lab.scd.xml.dom;
6  
7 import javax.xml.parsers.*;
8 import org.w3c.dom.*;
9  
10 public class TestDOM
11 {
12    public static void main( String [] args ) throws Exception
13    {
14       DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
15       DocumentBuilder parser = factory.newDocumentBuilder();
16       Document document = parser.parse( "persoana.xml" );
17       Element inventory = document.getDocumentElement();
18       NodeList lst = inventory.getElementsByTagName("persoana");
19  
20       System.out.println("Persoane:"+lst.getLength());
21       for( int i=0; i<lst.getLength(); i++ ) {
22          String n = DOMUtil.getSimpleElementText(
23             (Element)lst.item(i),"nume" );
24          String p = DOMUtil.getSimpleElementText(
25             (Element)lst.item(i), "prenume" );
26          System.out.println( "  "+ n +" ("+p+")" );
27       }
28  
29    }
30 }
31  
32 class DOMUtil
33 {
34    public static Element getFirstElement( Element element, String name ) {
35       NodeList nl = element.getElementsByTagName( name );
36       if ( nl.getLength() < 1 )
37          throw new RuntimeException(
38             "Element: "+element+" does not contain: "+name);
39       return (Element)nl.item(0);
40    }
41  
42    public static String getSimpleElementText( Element node, String name )
43    {
44       Element namedElement = getFirstElement( node, name );
45       return getSimpleElementText( namedElement );
46    }
47  
48    public static String getSimpleElementText( Element node )
49    {
50       StringBuffer sb = new StringBuffer();
51       NodeList children = node.getChildNodes();
52       for(int i=0; i<children.getLength(); i++) {
53          Node child = children.item(i);
54          if ( child instanceof Text )
55             sb.append( child.getNodeValue() );
56       }
57       return sb.toString();
58    }
59 }