VC + + Operation XML (MFC, SDK) go

Source: Internet
Author: User

Go VC + + Operation XML (MFC, SDK)

XML in the WIN32 program should not be used in the web, many of the WIN32 program is only using XML to store configuration information, and there is no good enough to use INI. VC + + Operation XML has two libraries that can be used: MSXML and XmlLite. MSXML also subdivides two interfaces: Dom and SAX2. XP does not come with XmlLite, only MSXML with 2.x, 3.x version, does not support SAX2 (requires MSXML 4.0 or more), so the DOM is preferred.
Dom is provided in the form of COM, VC + + call Dom can be divided into 3 ways:
1, MFC calls with CComPtr
2, the SDK directly call the DOM interface
3, the SDK with smart pointer calls
These 3 methods are essentially the same, except that the difference is just how much coding is needed, and that using ccomptr can greatly simplify the code, here are a few examples.
Example Stocks.xml:

<?XML version= "1.0" encoding= "Utf-8"?><Root><Node1>Text1</Node1><Node2><Childnode1ATTRIB1= "Value1"Attrib2= "value2"/><Childnode2ATTRIB1= "Value1"Attrib2= "value2">Childtext1</Childnode2></Node2></Root>

This example should contain the most common features of XML, right?
Mfc
MFC can directly use the DOM, do not need to manually add additional header files, only need to call CoInitialize (NULL) in cwinapp::initinstance () initialize COM, in CWinApp:: ExitInstance calls CoUninitialize () to release COM on the line.

Read XML

Ccomptr<ixmldomdocument> Spdoc;//DOMspdoc.cocreateinstance (clsid_domdocument); Variant_bool Vb;spdoc->load (CComVariant (OLESTR ("Stocks.xml")), &AMP;VB);//loading an XML fileCcomptr<ixmldomelement>Sprootele;spdoc->get_documentelement (&sprootele);//root nodeCcomptr<ixmldomnodelist>Spnodelist;sprootele->get_childnodes (&spnodelist);//child node ListLongnlen;spnodelist->get_length (&nlen);//number of child nodes for(Longi =0; I! = Nlen; ++i)//Traversing child nodes{CComPtr<IXMLDOMNode>spnode;spnodelist->get_item (i, &Spnode); Processnode (Spnode); //Node handler function}//Write XMLCcomptr<ixmldomnode>Spnode;sprootele->selectsinglenode (OLESTR ("/root/node1"), &spnode); Spnode->put_text (OLESTR ("NewText"));//Write TextSprootele->selectsinglenode (OLESTR ("/root/node2/childnode1/@attrib1"), &spnode); Spnode->put_nodevalue (CComVariant (OLESTR ("NewValue")));//Write ValueCcomptr<ixmldomnode>Spnewnode;spdoc->createnode (CComVariant (node_element), OLESTR ("Childnode3"), OLESTR (""), &spnewnode);//Create a new nodeSprootele->selectsinglenode (OLESTR ("/root/node2"), &spnode); Spnode->appendchild (Spnewnode, &spnewnode);//add a new node as a node2 child nodeSpnewnode->put_text (OLESTR ("childtext2"));//Write new node textccomqiptr<ixmldomelement> Spele = Spnewnode;//Note that ccomqiptr is used hereSpele->setattribute (OLESTR ("ATTRIB1"), CComVariant (OleStr ("value1")));//add a property to a new nodeSpdoc->save (CComVariant (OLESTR ("Stocks.xml")));//Node handler functionvoidProcessnode (ccomptr<ixmldomnode>&Spnode) {CComBSTR Bsnodename;spnode->get_nodename (&bsnodename);//Node nameAfxMessageBox (COLE2CT (bsnodename)); CComVariant Varval;spnode->get_nodevalue (&varval);//Node ValueAfxMessageBox (COLE2CT (varval.bstrval));D Omnodetype Enodetype;spnode->get_nodetype (&enodetype);if(Enodetype = = node_element)//only node_element types can contain attributes and child nodes{//recursive traversal of node propertiesCcomptr<ixmldomnamednodemap>Spnamenodemap;spnode->get_attributes (&spnamenodemap);LongNlength;spnamenodemap->get_length (&nlength); for(Longi =0; I! = nlength; ++i) {CCOMPTR<IXMLDOMNode> Spnodeattrib;//Note that the attribute is also a ixmldomnodeSpnamenodemap->get_item (i, &Spnodeattrib); Processnode (Spnodeattrib);}//recursively traverse child nodesCcomptr<ixmldomnodelist>Spnodelist;spnode->get_childnodes (&spnodelist); Spnodelist->get_length (&nlength); for(Longi =0; I! = nlength; ++i) {CCOMPTR<IXMLDOMNode>spchildnode;spnodelist->get_item (i, &Spchildnode); Processnode (Spchildnode); }}}

For a node such as <tag>text</tag>, Get_nodevalue will get empty, to get "text" words can traverse the child node (only a child node, its nodename is "#text", NodeType for Node_text,nodevalue is "text"), or you can use Get_text to get "text" directly, but for such a node <tag>text<childtag>childtext </childtag></tag>,get_text will also get "text" and "Childtext", but such nodes should not be allowed.
The string used in Dom (BSTR) is OLESTR type, by default olestr is Unicode character, MFC can use COLE2CT to convert LPCOLESTR to LPCTSTR.
For your own defined XML, most of the time you do not need to traverse, you can read a node or property directly by calling SelectNodes, selectSingleNode specify XPath:

Ccomptr<ixmldomdocument> Spdoc;//DOMspdoc.cocreateinstance (clsid_domdocument); Variant_bool Vb;spdoc->load (CComVariant (OLESTR ("Stocks.xml")), &AMP;VB);//loading an XML fileCcomptr<ixmldomelement>Sprootele;spdoc->get_documentelement (&sprootele);//root nodeCcomptr<ixmldomnodelist>spnodelist; CComPtr<IXMLDOMNode>Spnode;sprootele->selectnodes (OLESTR ("/root/node2/*"), &spnodelist);//get all the child nodes under the Node2Sprootele->selectsinglenode (OLESTR ("/root/node2/childnode1/@attrib1"), &spnode);//get the Attrib1 property of Childnode1

The syntax for XPath can refer to an XML document or MSDN.
Sdk
The SDK can also use smart pointers, and MFC is not much different, but also very convenient, directly to the code:

#include <iostream>#include<tchar.h>#import<msxml3.dll>//Node handler functionvoidProcessnode (msxml2::ixmldomnodeptr spnode) {std::cout<<"NodeName:"<< spnode->NodeName;if(Spnode->nodetype = = Node_attribute | | spnode->nodetype = =node_text) Std::cout<<"\tnodevalue:"<< _bstr_t (spnode->nodevalue); Std::cout<<Std::endl;if(Spnode->nodetype = =node_element) {msxml2::ixmldomnamednodemapptr Spnamenodemap= spnode->attributes; for(Longi =0; I! = spnamenodemap->length; ++i)//Traverse Node PropertiesProcessnode (spnamenodemap->Item[i]); Msxml2::ixmldomnodelistptr spnodelist= spnode->ChildNodes; for(Longi =0; I! = spnodelist->length; ++i)//Traversing child nodesProcessnode (spnodelist->item[i]);}}int_tmain (intARGC, _tchar*argv[]) {CoInitialize (NULL);//Read XMLmsxml2::ixmldomdocumentptr spxmldoc;spxmldoc.createinstance (__uuidof (MSXML2::D OMDocument30)); Spxmldoc->load (L"Stocks.xml"); Msxml2::ixmldomelementptr Sproot= spxmldoc->documentelement;//root nodeMsxml2::ixmldomnodelistptr spnodelist = sproot->ChildNodes; for(Longi =0; I! = spnodelist->length; ++i)//Traversing child nodesProcessnode (spnodelist->item[i]);//Write XMLSproot->selectsinglenode (L"/root/node1")->text = L"NewText"; Sproot->selectsinglenode (L"/root/node2/childnode1/@attrib1")->nodevalue = L"NewValue"; Msxml2::ixmldomnodeptr Spnewnode= Sproot->selectsinglenode (L"/root/node2"),appendchild (Spxmldoc->createnode (_variant_t (node_element), L"Childnode3", L"")); //Create a new child node for Node2 childnode3Spnewnode->text = L"childtext2"; Msxml2::ixmldomelementptr Spele=Spnewnode;spele->setattribute (L"ATTRIB1", _variant_t (L"value1"));//Add new PropertySpxmldoc->save (_variant_t (L"Stocks.xml") ; Spnewnode.release (); Spele.release (); Spnodelist.release (); Sproot.release (); Spxmldoc.release (); CoUninitialize (); System ("Pause");return 0;}

VC + + Operation XML (MFC, SDK) go

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.