Biblioteca Java - Blame information for rev 3
Subversion Repositories:
Rev | Author | Line No. | Line |
---|---|---|---|
3 | mihai | 1 | /* |
2 | * DomXmlExample.java | ||
3 | */ | ||
4 | package lab.scd.xml.dom; | ||
5 | |||
6 | /** | ||
7 | * Clasa exemplifica folosirea DOM pentru a construi documente in format XML. | ||
8 | */ | ||
9 | import java.io.*; | ||
10 | |||
11 | import org.w3c.dom.*; | ||
12 | |||
13 | import javax.xml.parsers.*; | ||
14 | |||
15 | import javax.xml.transform.*; | ||
16 | import javax.xml.transform.dom.*; | ||
17 | import javax.xml.transform.stream.*; | ||
18 | |||
19 | public class DomXmlExample { | ||
20 | |||
21 | /** | ||
22 | * Our goal is to create a DOM XML tree and then print the XML. | ||
23 | */ | ||
24 | public static void main (String args[]) { | ||
25 | new DomXmlExample(); | ||
26 | } | ||
27 | |||
28 | public DomXmlExample() { | ||
29 | try { | ||
30 | ///////////////////////////// | ||
31 | //Construieste un document XML gol | ||
32 | |||
33 | |||
34 | DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); | ||
35 | DocumentBuilder docBuilder = dbfac.newDocumentBuilder(); | ||
36 | Document doc = docBuilder.newDocument(); | ||
37 | |||
38 | //////////////////////// | ||
39 | //Construieste arborele XML | ||
40 | |||
41 | //constr. elementul root | ||
42 | Element root = doc.createElement("root"); | ||
43 | doc.appendChild(root); | ||
44 | |||
45 | //adauga comentariu in cadrul elementului root | ||
46 | Comment comment = doc.createComment("Un comentariu"); | ||
47 | root.appendChild(comment); | ||
48 | |||
49 | //adauga un element copil in root | ||
50 | Element child = doc.createElement("child"); | ||
51 | child.setAttribute("name", "value"); | ||
52 | root.appendChild(child); | ||
53 | |||
54 | //add a text element to the child | ||
55 | Text text = doc.createTextNode("Un sir de caractere adaugat in cadrul unui element!"); | ||
56 | child.appendChild(text); | ||
57 | |||
58 | ///////////////// | ||
59 | //Generare string XML | ||
60 | |||
61 | //construieste un obiect transformer | ||
62 | TransformerFactory transfac = TransformerFactory.newInstance(); | ||
63 | Transformer trans = transfac.newTransformer(); | ||
64 | trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); | ||
65 | trans.setOutputProperty(OutputKeys.INDENT, "yes"); | ||
66 | |||
67 | //construieste string pe baza arborelui XML | ||
68 | StringWriter sw = new StringWriter(); | ||
69 | StreamResult result = new StreamResult(sw); | ||
70 | DOMSource source = new DOMSource(doc); | ||
71 | trans.transform(source, result); | ||
72 | String xmlString = sw.toString(); | ||
73 | |||
74 | //print xml | ||
75 | System.out.println("Sir xml generat:\n\n" + xmlString); | ||
76 | |||
77 | } catch (Exception e) { | ||
78 | System.out.println(e); | ||
79 | } | ||
80 | } | ||
81 | } |