3 * synopsis: Creates a tree
4 * purpose: Shows how to create document, nodes and dump it to stdout or file.
5 * usage: tree2 <filename> -Default output: stdout
6 * test: tree2 > tree2.tmp && diff tree2.tmp $(srcdir)/tree2.res
7 * author: Lucas Brasilino <brasilino@recife.pe.gov.br>
8 * copy: see Copyright for the status of this software
12 #include <libxml/parser.h>
13 #include <libxml/tree.h>
15 #if defined(LIBXML_TREE_ENABLED) && defined(LIBXML_OUTPUT_ENABLED)
18 *To compile this file using gcc you can type
19 *gcc `xml2-config --cflags --libs` -o tree2 tree2.c
22 /* A simple example how to create DOM. Libxml2 automagically
23 * allocates the necessary amount of memory to it.
26 main(int argc
, char **argv
)
28 xmlDocPtr doc
= NULL
; /* document pointer */
29 xmlNodePtr root_node
= NULL
, node
= NULL
, node1
= NULL
;/* node pointers */
30 xmlDtdPtr dtd
= NULL
; /* DTD pointer */
37 * Creates a new document, a node and set it as a root node
39 doc
= xmlNewDoc(BAD_CAST
"1.0");
40 root_node
= xmlNewNode(NULL
, BAD_CAST
"root");
41 xmlDocSetRootElement(doc
, root_node
);
44 * Creates a DTD declaration. Isn't mandatory.
46 dtd
= xmlCreateIntSubset(doc
, BAD_CAST
"root", NULL
, BAD_CAST
"tree2.dtd");
49 * xmlNewChild() creates a new node, which is "attached" as child node
52 xmlNewChild(root_node
, NULL
, BAD_CAST
"node1",
53 BAD_CAST
"content of node 1");
55 * The same as above, but the new child node doesn't have a content
57 xmlNewChild(root_node
, NULL
, BAD_CAST
"node2", NULL
);
60 * xmlNewProp() creates attributes, which is "attached" to an node.
61 * It returns xmlAttrPtr, which isn't used here.
64 xmlNewChild(root_node
, NULL
, BAD_CAST
"node3",
65 BAD_CAST
"this node has attributes");
66 xmlNewProp(node
, BAD_CAST
"attribute", BAD_CAST
"yes");
67 xmlNewProp(node
, BAD_CAST
"foo", BAD_CAST
"bar");
70 * Here goes another way to create nodes. xmlNewNode() and xmlNewText
71 * creates a node and a text node separately. They are "attached"
74 node
= xmlNewNode(NULL
, BAD_CAST
"node4");
75 node1
= xmlNewText(BAD_CAST
76 "other way to create content (which is also a node)");
77 xmlAddChild(node
, node1
);
78 xmlAddChild(root_node
, node
);
81 * A simple loop that "automates" nodes creation
83 for (i
= 5; i
< 7; i
++) {
84 sprintf(buff
, "node%d", i
);
85 node
= xmlNewChild(root_node
, NULL
, BAD_CAST buff
, NULL
);
86 for (j
= 1; j
< 4; j
++) {
87 sprintf(buff
, "node%d%d", i
, j
);
88 node1
= xmlNewChild(node
, NULL
, BAD_CAST buff
, NULL
);
89 xmlNewProp(node1
, BAD_CAST
"odd", BAD_CAST((j
% 2) ? "no" : "yes"));
94 * Dumping document to stdio or file
96 xmlSaveFormatFileEnc(argc
> 1 ? argv
[1] : "-", doc
, "UTF-8", 1);
98 /*free the document */
102 *Free the global variables that may
103 *have been allocated by the parser.
108 * this is to debug memory for regression tests
115 fprintf(stderr
, "tree support not compiled in\n");