Biblioteca Java - Blame information for rev 3
Subversion Repositories:
Rev | Author | Line No. | Line |
---|---|---|---|
3 | mihai | 1 | package lab.scd.xml.sax; |
2 | import java.io.*; | ||
3 | import java.util.ArrayList; | ||
4 | |||
5 | import javax.xml.parsers.*; | ||
6 | import org.xml.sax.*; | ||
7 | import org.xml.sax.helpers.*; | ||
8 | |||
9 | public class SAXProcesorXML{ | ||
10 | public static void main(String[] args) { | ||
11 | |||
12 | // Contruieste un obiect de tip handler care va capta evenimentele generate in momentul parcurgerii documentului | ||
13 | DefaultHandler handler = new MyHandler(); | ||
14 | |||
15 | // procesare fisier xml utlizand handlerul construit anterios | ||
16 | parseXmlFile("persoana.xml", handler, false); | ||
17 | } | ||
18 | |||
19 | |||
20 | // Aceasta clasa trebuie sa suprascrie metodele din DefaultHandler | ||
21 | static class MyHandler extends DefaultHandler { | ||
22 | |||
23 | public void endElement(String uri, String localName, String qName) | ||
24 | throws SAXException { | ||
25 | |||
26 | System.err.println("Sfarsit element:"+qName); | ||
27 | } | ||
28 | |||
29 | /** | ||
30 | * In momentul inceperi parcurgerii documentului este generat evenimentul start document | ||
31 | * care va fi captat de aceasta metoda. In cadrul ei se initializeaza un vector | ||
32 | */ | ||
33 | public void startDocument() throws SAXException { | ||
34 | System.err.println("*Start procesare document"); | ||
35 | } | ||
36 | |||
37 | public void startElement(String uri, String localName, String qName, | ||
38 | Attributes attributes) throws SAXException { | ||
39 | |||
40 | System.err.println("Start element:"+qName); | ||
41 | } | ||
42 | |||
43 | public void characters(char[] ch, int start, int length) | ||
44 | throws SAXException { | ||
45 | System.err.println("Continut:"+new String(ch,start,length)); | ||
46 | } | ||
47 | } | ||
48 | |||
49 | // Parses an XML file using a SAX parser. | ||
50 | // If validating is true, the contents is validated against the DTD | ||
51 | // specified in the file. | ||
52 | public static void parseXmlFile(String filename, DefaultHandler handler, boolean validating) { | ||
53 | try { | ||
54 | |||
55 | SAXParserFactory factory = SAXParserFactory.newInstance(); | ||
56 | factory.setValidating(validating); | ||
57 | |||
58 | // contruieste procesorul si incepe validarea fisir | ||
59 | // fisiserul este parcurs si va fi generate evenimente in momentul parcurgerii acestui fisier xml | ||
60 | // evenimentele vor fi captate de catre MyHandler | ||
61 | factory.newSAXParser().parse(new File(filename), handler); | ||
62 | } catch (SAXException e) { | ||
63 | e.printStackTrace(); | ||
64 | } catch (ParserConfigurationException e) { | ||
65 | e.printStackTrace(); | ||
66 | } catch (IOException e) { | ||
67 | e.printStackTrace(); | ||
68 | } | ||
69 | } | ||
70 | } | ||
71 |