Use libxml2 to create, modify, and search for XML

Source: Internet
Author: User

 

The project must implement a background for managing XML files Program You need to create, parse, modify, and search XML files. The following describes how to use the library provided by libxml2 to implement the above functions. 1. Create an XML document: We use xmlnewdoc () to create an XML document, and then use xmlnewnode (), xmlnewchild (), xmlnewprop (), xmlnewtext () add nodes and subnodes to the XML file, set the elements and attributes, and use xmlsaveformatfileenc () to save the XML file to the disk (this function can set the encoding format when saving the XML file ). Example 1: # include <stdio. h> # include <libxml/parser. h> # include <libxml/tree. h> int main (INT argc, char ** argv) {xmldocptr Doc = NULL;/* Document pointer */xmlnodeptr root_node = NULL, node = NULL, node1 = NULL; /* node pointers * // creates a new document, a node and set it as a root node Doc = xmlnewdoc (bad_cast "1.0"); root_node = xmlnewnode (null, bad_cast "root"); xmldocsetrootelement (Doc, root _ Node); // creates a new node, which is "attached" as child node of root_node node. xmlnewchild (root_node, null, bad_cast "node1", bad_cast "content of node1"); // xmlnewprop () creates attributes, which is "attached" to an node. node = xmlnewchild (root_node, null, bad_cast "node3", bad_cast "node has attributes"); xmlnewprop (node, bad_cast "attribute", bad_cast "yes "); // here goes another way to create Nodes. node = xmlnewnode (null, bad_cast "node4"); node1 = xmlnewtext (bad_cast "other way to create content"); xmladdchild (node, node1); xmladdchild (root_node, node ); // dumping document to stdio or file xmlsaveformatfileenc (argc> 1? Argv [1]: "-", Doc, "UTF-8", 1);/* free the document */xmlfreedoc (DOC); xmlcleanupparser (); xmlmemorydump (); // debug memory for regression tests return (0);} 2. When parsing an XML document, you only need to file names and call only one function, and check for errors, common related functions include xmlparsefile () and xmlparsedoc (). After obtaining the document pointer, you can use xmldocgetrootelement () to obtain the node pointer of the root element, you can use this pointer to roam in the DOM tree. After the pointer is completed, you need to call xmlfreedoc () to release it. Example 2: xmldocptr Doc; // defines the parsing document pointer xmlnodeptr cur; // defines the node pointer (you need it to move between nodes) xmlchar * key; doc = xmlreadfile (URL, my_encoding, 256); // parse the file/* check whether the parsing document is successful. If it fails, libxml indicates a registered error and stops. A common error is improper encoding. XML standard documents can be saved in other encodings in addition to UTF-8 or UTF-16. If so, libxml will automatically convert you to the UTF-8. More information about XML encoding is included in the XML standard. */If (Doc = NULL) {fprintf (stderr, "document not parsed successfully. \ n "); return;} cur = xmldocgetrootelement (DOC); // determine the document root element/* check and confirm that the current document contains content */If (cur = NULL) {fprintf (stderr, "empty document \ n"); xmlfreedoc (DOC); return;}/* in this example, we need to confirm that the document is of the correct type. "Root" is the root type of the document used in this example. */If (xmlstrcmp (cur-> name, (const xmlchar *) "root") {fprintf (stderr, "Document of the wrong type, root node! = Root "); xmlfreedoc (DOC); return;} cur = cur-> xmlchildrennode; while (cur! = NULL) {If ((! Xmlstrcmp (cur-> name, (const xmlchar *) "keyword") {key = xmlnodelistgetstring (Doc, cur-> xmlchildrennode, 1); printf ("Keyword: % s \ n ", key); xmlfree (key);} cur = cur-> next;} xmlfreedoc (DOC ); 3. Search for XML nodes. Sometimes, for an XML document, we may only care about the values or attributes of one or more specific elements, it would be very painful and boring to roam the DOM tree. Using XPath can easily get the element you want. The following is a custom function: Example 3: // includes the header file # include ". /include/libxml/XPath. H "xmlxpathobjectptr get_nodeset (xmldocptr doc, const xmlchar * XPath) {xmlxpathcontextptr context; xmlxpathobjectptr result; Context = xmlxpathnewcontext (DOC); If (context = NULL) {printf ("context is null \ n"); return NULL;} result = xmlxpathevalexpression (XPath, context); xmlxpathfreecontext (context); If (result = NULL) {printf ("xmlxpathe Valexpression return NULL \ n "); return NULL;} If (xmlxpathnodesetisempty (result-> nodesetval) {xmlxpathfreeobject (result); printf (" nodeset is empty \ n "); return NULL;} return result;} query the nodes that meet the XPath expression conditions in the XML document to which the doc points, for information on how to write an XPATH query condition for a node set that meets this condition, see XPath. After obtaining the result set, you can access the node through the returned xmlxpathobjectptr structure: Example 4: xmlchar * XPath = ("/root/node/wanmac "); xmlxpathobjectptr app_result = get_nodeset (Doc, XPath); If (app_result = NULL) {printf ("app_result is null \ n"); return;} int I = 0; xmlchar * value; If (app_result) {xmlnodesetptr nodeset = app_result-> nodesetval; for (I = 0; I <nodeset-> nodenr; I ++) {cur = nodeset-> nodetab [I]; cur = cur-> xmlchildrennode; W Hile (cur! = NULL) {value = xmlgetprop (cur, (const xmlchar *) "wanmac"); If (value! = NULL) {printf ("value1: % s \ n", value); xmlfree (value);} value = xmlnodegetcontent (cur); If (value! = NULL) {printf ("value2: % s \ n", value); xmlfree (value) ;}cur = cur-> next ;}} xmlxpathfreeobject (app_result);} through the result set returned by get_nodeset (), we can get the elements and attributes of the node, or modify the value of the node. 4. To modify XML elements and attributes, you must first parse the XML document to obtain a node pointer (xmlnodeptr node ), using this node pointer to roam the DOM tree, you can get, modify, and add relevant information in the XML document. Example 6: Get the content of a node: xmlchar * value = xmlnodegetcontent (node); The returned value should use xmlfree (value) to release the memory to get a certain attribute value of a node: xmlchar * value = xmlgetprop (node, (const xmlchar *) "prop1"); the returned value requires xmlfree (value) to release the memory and set the content of a node: xmlnodesetcontent (node, (const xmlchar *) "test"); set the attribute value of a node: xmlsetprop (node, (const xmlchar *) "prop1", (const xmlchar *) "V1 "); add a node element: xmlnewtextchild (node, null, (const xmlchar *) "keyword", (const xmlchar *) "test element"); add a node attribute: xmlnewprop (node, (const xmlchar *) "prop1", (const xmlchar *) "test element"); this article is from the csdn blog. For more information, see file: // C: /Documents % 20and % 20 settings/ASDF/desktop/web/use libxml2000020create, modify, search for the 20-20csdnblog .htm of xml1_20-000020m1_2607.

To implement a background program for XML file management in the project, you need to create, parse, modify, and search the XML file. The following describes how to use the library provided by libxml2 to implement the above functions. 1. Create an XML document:
We use xmlnewdoc () to create an XML document, and then use functions such as xmlnewnode (), xmlnewchild (), xmlnewprop (), and xmlnewtext () to add nodes and subnodes to the XML file, set the elements and attributes. After creation, use xmlsaveformatfileenc () to save the XML file to the disk (this function can set the encoding format when saving the XML file ).
Example 1:
# Include <stdio. h>
# Include <libxml/parser. h>
# Include <libxml/tree. h>
Int main (INT argc, char ** argv)
{
Xmldocptr Doc = NULL;/* Document pointer */
Xmlnodeptr root_node = NULL, node = NULL, node1 = NULL;/* node pointers */
// Creates a new document, a node and set it as a root node
Doc = xmlnewdoc (bad_cast "1.0 ");
Root_node = xmlnewnode (null, bad_cast "root ");
Xmldocsetrootelement (Doc, root_node );
// Creates a new node, which is "attached" as child node of root_node node.
Xmlnewchild (root_node, null, bad_cast "node1", bad_cast "content of node1 ");
// Xmlnewprop () creates attributes, which is "attached" to an node.
Node = xmlnewchild (root_node, null, bad_cast "node3", bad_cast "node has attributes ");
Xmlnewprop (node, bad_cast "attribute", bad_cast "yes ");
// Here goes another way to create nodes.
Node = xmlnewnode (null, bad_cast "node4 ");
Node1 = xmlnewtext (bad_cast "other way to create content ");
Xmladdchild (node, node1 );
Xmladdchild (root_node, node );
// Dumping document to stdio or file
Xmlsaveformatfileenc (argc> 1? Argv [1]: "-", Doc, "UTF-8", 1 );
/* Free the document */
Xmlfreedoc (DOC );
Xmlcleanupparser ();
Xmlmemorydump (); // debug memory for regression tests
Return (0 );
}

2. parse XML documents
When parsing a document, you only need a file name and only call one function, and check for errors. Common related functions include xmlparsefile () and xmlparsedoc (). After obtaining the document pointer, you can use xmldocgetrootelement () to obtain the node pointer of the root element. With this pointer, You can roam in the DOM tree and call xmlfreedoc () to release the node.
Example 2:
Xmldocptr Doc; // defines the parsing document pointer
Xmlnodeptr cur; // defines the node pointer (you need it to move between nodes)
Xmlchar * key;
Doc = xmlreadfile (URL, my_encoding, 256); // parse the file

/* Check whether the parsing document is successful. If it fails, libxml indicates a registered error and stops. A common error is improper encoding. XML standard documents can be saved in other encodings in addition to UTF-8 or UTF-16. If so, libxml will automatically convert you to the UTF-8. More information about XML encoding is included in the XML standard. */
If (Doc = NULL ){
Fprintf (stderr, "document not parsed successfully. \ n ");
Return;
}
Cur = xmldocgetrootelement (DOC); // determine the document root element
/* Check and confirm that the current document contains content */
If (cur = NULL ){
Fprintf (stderr, "empty document \ n ");
Xmlfreedoc (DOC );
Return;
}
/* In this example, we need to confirm that the document is of the correct type. "Root" is the root type of the document used in this example. */
If (xmlstrcmp (cur-> name, (const xmlchar *) "root ")){
Fprintf (stderr, "Document of the wrong type, root node! = Root ");
Xmlfreedoc (DOC );
Return;
}

Cur = cur-> xmlchildrennode;
While (cur! = NULL ){
If ((! Xmlstrcmp (cur-> name, (const xmlchar *) "keyword "))){
Key = xmlnodelistgetstring (Doc, cur-> xmlchildrennode, 1 );
Printf ("Keyword: % s \ n", key );
Xmlfree (key );
}
Cur = cur-> next;
}
Xmlfreedoc (DOC );


3. Search for XML nodes
Sometimes, for an XML document, we may only care about the values or attributes of one or more specific elements. It will be very painful and boring to roam the DOM tree, using XPath, you can easily get the element you want. The following is a UDF:
Example 3:
// Includes the header file
# Include "./include/libxml/XPath. H"
Xmlxpathobjectptr get_nodeset (xmldocptr doc, const xmlchar * XPath ){
Xmlxpathcontextptr context;
Xmlxpathobjectptr result;
Context = xmlxpathnewcontext (DOC );
If (context = NULL ){
Printf ("context is null \ n ");
Return NULL;
}
Result = xmlxpathevalexpression (XPath, context );
Xmlxpathfreecontext (context );
If (result = NULL ){
Printf ("xmlxpathevalexpression return NULL \ n ");
Return NULL;
}
If (xmlxpathnodesetisempty (result-> nodesetval )){
Xmlxpathfreeobject (result );
Printf ("nodeset is empty \ n ");
Return NULL;
}
Return result;
}

Query the nodes that meet the criteria of the XPath expression in the XML document to which the doc points. For the method of returning the node set query criteria that meet the criteria, see relevant XPath documents. After obtaining the result set, you can access the node through the returned xmlxpathobjectptr structure:
Example 4:
Xmlchar * XPath = ("/root/node/wanmac ");
Xmlxpathobjectptr app_result = get_nodeset (Doc, XPath );
If (app_result = NULL ){
Printf ("app_result is null \ n ");
Return;
}

Int I = 0;
Xmlchar * value;
If (app_result ){
Xmlnodesetptr nodeset = app_result-> nodesetval; for (I = 0; I <nodeset-> nodenr; I ++) {cur = nodeset-> nodetab [I]; cur = cur-> xmlchildrennode;
While (cur! = NULL) {value = xmlgetprop (cur, (const xmlchar *) "wanmac"); If (value! = NULL) {printf ("value1: % s \ n", value); xmlfree (value);} value = xmlnodegetcontent (cur); If (value! = NULL) {printf ("value2: % s \ n", value); xmlfree (value) ;}cur = cur-> next ;}}
Xmlxpathfreeobject (app_result );}
Through the result set returned by get_nodeset (), we can obtain the elements and attributes of the node, or modify the value of the node.


4. Modify XML elements and attributes
to modify the elements and attributes of an XML document, you must first parse the XML document, get a node pointer (xmlnodeptr node). With this node pointer roaming the DOM tree, you can get, modify, and add relevant information in the XML document.
Example 6:
get the content of a node:
xmlchar * value = xmlnodegetcontent (node);
the returned value should use xmlfree (value) release memory
get a node attribute value:
xmlchar * value = xmlgetprop (node, (const xmlchar *) "prop1 ");
the returned value requires xmlfree (value) to release memory
set the content of a node:
xmlnodesetcontent (node, (const xmlchar *) "test ");
set the attribute value of a node:
xmlsetprop (node, (const xmlchar *) "prop1", (const xmlchar *) "V1 ");
Add a node element:
xmlnewtextchild (node, null, (const xmlchar *) "keyword", (const xmlchar *) "test element ");
Add a node attribute:
xmlnewprop (node, (const xmlchar *) "prop1", (const xmlchar *) "test element");

This article is from the csdn blog. For more information, see file: // C:/Documents % 20and % 20 settings/ASDF/desktop/web/templates.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.