|
Packit |
423ecb |
<html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><title>Writing element content</title><meta name="generator" content="DocBook XSL Stylesheets V1.61.2"><link rel="home" href="index.html" title="Libxml Tutorial"><link rel="up" href="index.html" title="Libxml Tutorial"><link rel="previous" href="ar01s05.html" title="Using XPath to Retrieve Element Content"><link rel="next" href="ar01s07.html" title="Writing Attribute"></head><body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
|
|
Packit |
423ecb |
Writing element content uses many of the same steps we used above
|
|
Packit |
423ecb |
— parsing the document and walking the tree. We parse the document,
|
|
Packit |
423ecb |
then traverse the tree to find the place we want to insert our element. For
|
|
Packit |
423ecb |
this example, we want to again find the "storyinfo" element and
|
|
Packit |
423ecb |
this time insert a keyword. Then we'll write the file to disk. Full code:
|
|
Packit |
423ecb |
Appendix E, Code for Add Keyword Example
|
|
Packit |
423ecb |
The main difference in this example is in
|
|
Packit |
423ecb |
<tt class="function">parseStory</tt>:
|
|
Packit |
423ecb |
|
|
Packit |
423ecb |
|
|
Packit |
423ecb |
void
|
|
Packit |
423ecb |
parseStory (xmlDocPtr doc, xmlNodePtr cur, char *keyword) {
|
|
Packit |
423ecb |
|
|
Packit |
423ecb |
xmlNewTextChild (cur, NULL, "keyword", keyword);
|
|
Packit |
423ecb |
return;
|
|
Packit |
423ecb |
}
|
|
Packit |
423ecb |
|
|
Packit |
423ecb |
|
|
Packit |
423ecb |
function adds a new child element at the
|
|
Packit |
423ecb |
current node pointer's location in the
|
|
Packit |
423ecb |
tree, specified by <tt class="varname">cur</tt>.
|
|
Packit |
423ecb |
|
|
Packit |
423ecb |
|
|
Packit |
423ecb |
Once the node has been added, we would like to write the document to
|
|
Packit |
423ecb |
file. Is you want the element to have a namespace, you can add it here as
|
|
Packit |
423ecb |
well. In our case, the namespace is NULL.
|
|
Packit |
423ecb |
|
|
Packit |
423ecb |
xmlSaveFormatFile (docname, doc, 1);
|
|
Packit |
423ecb |
|
|
Packit |
423ecb |
The first parameter is the name of the file to be written. You'll notice
|
|
Packit |
423ecb |
it is the same as the file we just read. In this case, we just write over
|
|
Packit |
423ecb |
the old file. The second parameter is a pointer to the xmlDoc
|
|
Packit |
423ecb |
structure. Setting the third parameter equal to one ensures indenting on output.
|
|
Packit |
423ecb |
</body></html>
|