一、用Poco庫
Poco庫是下載、編譯和使用:www.cnblogs.com/htj10/p/11380144.html
DOM(The Document Object Model)方式:
1. 生成XML
#include <Poco/AutoPtr.h> #include <Poco/DOM/Document.h> //for Poco::XML::Document #include <Poco/DOM/Element.h> //for Poco::XML::Element #include <Poco/DOM/Text.h> //for Poco::XML::Text #include <Poco/DOM/CDATASection.h> //for Poco::XML::CDATASection #include <Poco/DOM/ProcessingInstruction.h> //for Poco::XML::ProcessingInstruction #include <Poco/DOM/Comment.h> //for Poco::XML::Comment #include <Poco/DOM/DOMWriter.h> //for Poco::XML::DOMWriter #include <Poco/XML/XMLWriter.h> //for Poco::XML::XMLWriter #include <sstream> int main(int argc, char** argv) { //Poco生成XML Poco::AutoPtr<Poco::XML::Document> pDoc = new Poco::XML::Document; Poco::AutoPtr<Poco::XML::ProcessingInstruction> pi = pDoc->createProcessingInstruction("xml","version='1.0' encoding='UTF-8'"); Poco::AutoPtr<Poco::XML::Comment> pComment = pDoc->createComment("The information of some Universities."); Poco::AutoPtr<Poco::XML::Element> pRoot = pDoc->createElement("University_info"); Poco::AutoPtr<Poco::XML::Element> pChild = pDoc->createElement("University"); pChild->setAttribute("name", "Harvard"); Poco::AutoPtr<Poco::XML::Element> pGrandchild1 = pDoc->createElement("school"); pGrandchild1->setAttribute("name", "Secient"); Poco::AutoPtr<Poco::XML::Element> pGrandchild2 = pDoc->createElement("school"); pGrandchild2->setAttribute("name", "Mathematics"); Poco::AutoPtr<Poco::XML::Element> pNumOfPeople = pDoc->createElement("people_counting"); Poco::AutoPtr<Poco::XML::Text> pText = pDoc->createTextNode("123"); pNumOfPeople->appendChild(pText); Poco::AutoPtr<Poco::XML::CDATASection> pCDATA = pDoc->createCDATASection("sql=select * from table1 where id<5"); pDoc->appendChild(pi); pDoc->appendChild(pComment); pDoc->appendChild(pRoot); pRoot->appendChild(pChild); pChild->appendChild(pGrandchild1); pChild->appendChild(pGrandchild2); pGrandchild1->appendChild(pNumOfPeople); pRoot->appendChild(pCDATA); Poco::XML::DOMWriter writer; writer.setOptions(Poco::XML::XMLWriter::PRETTY_PRINT);// PRETTY_PRINT = 4 writer.writeNode("./example.xml", pDoc);//直接寫進文件 //或者直接寫進string std::stringstream sstr; writer.writeNode(sstr, pDoc); std::string s = sstr.str(); return 0; }
2. 解析xml (注意:只能對 Poco::XML::Document 使用智能指針 AutoPtr,或者delete,否則出現多次析構錯誤)
所以,除了Document的指針,其他Node,Attr什么的千萬別用智能指針。
引用:https://blog.csdn.net/qq_30811835/article/details/81939392
//解析xml std::string strXml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><!--this is a comment.--><books><book category = \"children\" language = \"English\" name = \"123English\"><title>Harry Potter</title><author>J.K. Rowling</author><price>29.99</price></book><function><![CDATA[bool cmp(int a, int b) {return a<b;}]]></function></books>"; Poco::XML::DOMParser parser; //parser.setFeature(Poco::XML::DOMParser::FEATURE_FILTER_WHITESPACE, true);//過濾空白符 //Poco::AutoPtr<Poco::XML::Document> pDoc = parser.parse("./example.xml");//解析xml文件 Poco::AutoPtr<Poco::XML::Document> pDoc = parser.parseString(strXml);//解析xml字符串 //獲取特定name的元素 //Poco::AutoPtr<Poco::XML::Node> pNode = pDoc->firstChild();//出錯!!別用智能指針 Poco::XML::Node* pNode = pDoc->firstChild();//正確 //通過Path獲取元素 Poco::XML::Element* elem = (Poco::XML::Element*)(pDoc->getNodeByPath("books/book"));//同樣別用智能指針 std::string s1 = elem->getAttribute("language");//"English" std::string s2 = elem->getAttribute("category");//"children" std::string s3 = elem->getChildElement("author")->innerText();//J.K. Rowling std::string s4 = elem->getChildElement("price")->innerText();//29.99 std::string s5 = elem->getNodeByPath("title")->innerText();//Harry Potter
#include <Poco/AutoPtr.h> //fro Poco::AutoPtr #include <Poco/DOM/Document.h> //for Poco::XML::Document #include <Poco/DOM/DOMParser.h> //for Poco::XML::DOMParser #include <Poco/DOM/NodeIterator.h> //for Poco::XML::NodeIterator #include <Poco/DOM/NodeFilter.h> //for Poco::XML::NodeFilter #include <Poco/DOM/Node.h> //for Poco::XML::Node #include <Poco/DOM/NamedNodeMap.h> //for Poco::XML::NamedNodeMap int main(int argc, char** argv) { //解析xml Poco::XML::DOMParser parser; //parser.setFeature(Poco::XML::DOMParser::FEATURE_FILTER_WHITESPACE, true);//過濾空白符 Poco::AutoPtr<Poco::XML::Document> pDoc = parser.parse("./example.xml");//解析xml文件 //Poco::AutoPtr<Poco::XML::Document> pDoc = parser.parseString(strXml);//解析xml字符串 Poco::XML::NodeIterator it(pDoc, Poco::XML::NodeFilter::SHOW_ALL);//可以過濾 SHOW_ELEMENT SHOW_ATTRIBUTE SHOW_TEXT SHOW_CDATA_SECTION 等 Poco::XML::Node* pNode = it.nextNode(); while (pNode) { //if (pNode->nodeType() != Poco::XML::Node::ELEMENT_NODE)//過濾 非element // {pNode = it.nextNode(); continue;} std::string sName = pNode->nodeName(); std::string sValue = pNode->nodeValue(); std::string sText = pNode->innerText(); Poco::XML::NamedNodeMap* map = pNode->attributes(); if (map) { for (int i = 0; i < map->length(); ++i) { Poco::XML::Node* attr = map->item(i); std::string sAttrName = attr->nodeName(); std::string sAttrValue = attr->nodeValue(); //... } } pNode = it.nextNode(); } return 0; }
節點 | nodeName | nodeValue |
Document | "#document" | "" |
Comment | "#comment" | "" |
Element | tag名 | "" |
Text | "#text" | 文本字符串 |
CDATASection | "#cdata-section" | CDATA內容 |
任何元素都被抽象成Node,同時又分為三種類型的節點。(Attr和Notation看成一種)
第一種類型:CharacterData,這類Node是Name不可變,而Value可以由用戶自定義。
第二種類型:AbstractContainerNode,這類Node有個特點,即含有屬性,特別的對於Element節點,Name可以由用戶自定義,而Value不可變。
第三種類型:右邊兩個,它們既可以改變Name,也可以改變Value。
————————————————
原文鏈接:https://blog.csdn.net/ma52103231/article/details/7701880
SAM(The Simple API for XML)方式:
參考官方文檔:https://pocoproject.org/slides/170-XML.pdf
二、tinyXml
下載:https://sourceforge.net/projects/tinyxml/
解壓縮tinyXML后,將這六個文件添加到你的C++工程中,分別是tinystr.h、tinystr.cpp、tinyxml.h、tinyxml.cpp、tinyxmlerror.cpp、tinyxmlparser.cpp。在需要操作xml文件的地方,使用如下代碼,就可以引入TinyXML類庫。 #include<tinyxml> 或 #include "tinyxml.h"
讀xml:

try { //TiXmlDocument *myDocument = new TiXmlDocument(fullPath.c_str());//這樣最后要delete myDocument //myDocument->LoadFile(); TiXmlDocument doc; //doc.LoadFile("info.xml"); string str("<Persons>\ <Person ID = '1' other = 'info'>\ <name>Michael</name>\ <age>23</age>\ </Person>\ </Persons>"); doc.Parse(str.c_str());//解析xml字符串 TiXmlElement *RootElement = doc.RootElement(); string root = RootElement->Value(); TiXmlElement *FirstPerson = RootElement->FirstChildElement(); TiXmlElement *NameElement = FirstPerson->FirstChildElement(); TiXmlElement *AgeElement = NameElement->NextSiblingElement(); TiXmlAttribute *IDAttribute = FirstPerson->FirstAttribute(); string name = NameElement->FirstChild()->Value();//或NameElement->GetText() string age = AgeElement->FirstChild()->Value();//或AgeElement->GetText() string attrName = IDAttribute->Name(); //"ID" string attrValue = IDAttribute->Value(); //"1" attrName = IDAttribute->Next()->Name(); //"other" attrValue = IDAttribute->Next()->Value();//"info" //delete myDocument; } catch (string& e) { return false; } return true;
寫xml:

try { TiXmlDocument *myDocument = new TiXmlDocument(); TiXmlElement *RootElement = new TiXmlElement("Persons"); myDocument->LinkEndChild(RootElement); TiXmlElement *PersonElement = new TiXmlElement("Person"); RootElement->LinkEndChild(PersonElement); PersonElement->SetAttribute("ID", "1"); PersonElement->SetAttribute("other", "info"); TiXmlElement *NameElement = new TiXmlElement("name"); TiXmlElement *AgeElement = new TiXmlElement("age"); PersonElement->LinkEndChild(NameElement); PersonElement->LinkEndChild(AgeElement); TiXmlText *NameContent = new TiXmlText("Michael"); TiXmlText *AgeContent = new TiXmlText("23"); NameElement->LinkEndChild(NameContent); AgeElement->LinkEndChild(AgeContent); CString appPath = GetAppPath(); string seperator = "\\"; string fullPath = appPath.GetBuffer(0) + seperator + szFileName; myDocument->SaveFile(fullPath.c_str()); delete myDocument; } catch (string& e) { return false; } return true;
讀寫xml
<?xml version="1.0" encoding="utf-8" ?> <!--this is a comment.--> <books> <book category="children" language="English" name="123English"> <title>Harry Potter</title> <anthor>J.K. Rowling</anthor> <price>29.99</price> </book> <function> <![CDATA[bool cmp(int a,int b) {return a<b;}]]> </function> </books>

try { TiXmlDocument* doc = new TiXmlDocument; TiXmlDeclaration* decl = new TiXmlDeclaration("1.0", "utf-8", ""); doc->LinkEndChild(decl); TiXmlComment* pComment = new TiXmlComment("this is a comment."); doc->LinkEndChild(pComment); TiXmlElement *root, *elem, *child; TiXmlText *text; root = new TiXmlElement("books"); doc->LinkEndChild(root); elem = new TiXmlElement("book"); elem->SetAttribute("category", "children"); elem->SetAttribute("language", "English"); elem->SetAttribute("name", "123English");//可以解出來123,但“English123”不能 root->LinkEndChild(elem); child = new TiXmlElement("title"); text = new TiXmlText("Harry Potter"); child->LinkEndChild(text); elem->LinkEndChild(child); child = new TiXmlElement("anthor"); text = new TiXmlText("J.K. Rowling"); child->LinkEndChild(text); elem->LinkEndChild(child); child = new TiXmlElement("price"); text = new TiXmlText("29.99"); child->LinkEndChild(text); elem->LinkEndChild(child); //一個CDATA(Tixml看做是TiXmlText) elem = new TiXmlElement("function"); TiXmlText* pCDATA = new TiXmlText("bool cmp(int a,int b)\n{return a<b;}"); pCDATA->SetCDATA(true); elem->LinkEndChild(pCDATA); root->LinkEndChild(elem); //doc->Print();//打印到 stdout cout doc->SaveFile("D:\\test.xml");//輸出到文件 TiXmlPrinter printer; //printer.SetStreamPrinting();//有這句,無空白符,就一行字符串 doc->Accept(&printer); string sRet = printer.CStr();//輸出到字符串 delete doc;//只需要這一個delete,它的所有子節點都delete了 {//解析 string sXml = sRet; TiXmlDocument doc; ////解析xml字符串 //doc.Parse(sXml.c_str()); //if (doc.Error()) // return false; //解析xml文件 if (!doc.LoadFile("D:\\test.xml")) return false; TiXmlElement* root = doc.RootElement(); TiXmlElement* elem = root->FirstChildElement(); //遍歷 for (TiXmlElement* tmp = elem->FirstChildElement(); tmp; tmp = tmp->NextSiblingElement()) { string s = tmp->Value(); const char* p = tmp->GetText(); string t(p ? p : ""); } //查找特定name的元素 TiXmlElement* elem2 = root->FirstChildElement("book"); //遍歷Attribute for (TiXmlAttribute* pAttr = elem2->FirstAttribute(); pAttr; pAttr = pAttr->Next()) { string sName = pAttr->Name(); string sValue = pAttr->Value(); } //獲取特定attribute const char* psz1 = elem2->Attribute("language");//"English" const char* psz2 = elem2->Attribute("category");//"children",若沒有找到"category"屬性,則返回NULL //還有,直接取值的 int i; elem2->Attribute("name", &i);//返回const char* , 失敗返回NULL double d; elem2->Attribute("name", &d); elem2->QueryIntAttribute("name", &i); elem2->QueryDoubleAttribute("name", &d); bool b; elem2->QueryBoolAttribute("name", &b); //... //獲取CDATA TiXmlElement* elem3 = root->FirstChildElement("function"); string ss = elem3->GetText(); string ss2 = elem3->FirstChild()->Value();//或者 } } catch (std::string& e) { return false; }
www.cnblogs.com/phinecos/archive/2008/03/11/1100912.html
www.cnblogs.com/MakeView660/p/6038173.html
三、CMarkup
官網下載地址:http://www.firstobject.com/dn_markup.htm
網盤鏈接:https://pan.baidu.com/s/1VP-eo-SWkKChC6dhMmTakA 提取碼:36pg
直接將 Markup.h 和 Markup.cpp 包含到工程中就可以使用了。
生成:
// VS2013,新建win32 console 空程序,添加Markup.h和Markup.cpp , 並設置工程屬性,設置 MFC的使用: 在共享DLL中使用MFC #include "Markup.h" int main() { CMarkup xml; xml.AddElem(_T("ORDER")); xml.AddChildElem(_T("ITEM")); xml.IntoElem(); xml.AddChildElem(_T("SN"), _T("132487A-J")); xml.AddChildElem(_T("NAME"), _T("crank casing")); xml.AddChildElem(_T("QTY"), _T("1")); xml.OutOfElem(); xml.AddChildElem(_T("PERSON")); xml.IntoElem(); xml.SetAttrib(_T("name"), _T("Lee")); CString csXML = xml.GetDoc(); xml.Save(_T("test.xml")); return 0; } /*結果 <ORDER> <ITEM> <SN>132487A-J</SN> <NAME>crank casing</NAME> <QTY>1</QTY> </ITEM> <PERSON name="Lee"/> </ORDER> */
解析xml:
// VS2013 , 屬性設置 MFC的使用: 在共享DLL中使用MFC #include "Markup.h" #include <map> #include <utility> // std::pair using std::map; using std::pair; int main() { //CMarkup xml; //xml.AddElem(_T("ORDER")); //xml.AddChildElem(_T("ITEM")); //xml.IntoElem(); //xml.AddChildElem(_T("SN"), _T("132487A-J")); //xml.AddChildElem(_T("NAME"), _T("crank casing")); //xml.AddChildElem(_T("QTY"), _T("1")); //xml.OutOfElem(); //xml.AddChildElem(_T("PERSON")); //xml.IntoElem(); //xml.SetAttrib(_T("name"), _T("Lee")); //CString csXML = xml.GetDoc(); //xml.Save(_T("test.xml")); CMarkup xml; xml.Load(_T("test.xml")); //xml.SetDoc(strXML);//加載字符串xml //查找特定元素 while (xml.FindChildElem(_T("ITEM"))) { xml.IntoElem(); xml.FindChildElem(_T("SN")); CString csSN = xml.GetChildData(); xml.FindChildElem(_T("QTY")); int nQty = _ttoi(xml.GetChildData()); xml.OutOfElem(); } xml.ResetPos(); // top of document xml.FindElem(); // ORDER element is root xml.IntoElem(); xml.FindElem();// ITEM element xml.IntoElem(); map<CString, CString> mapData; while (xml.FindElem()) { CString strName = xml.GetTagName(); CString strData = xml.GetData(); mapData.insert(std::make_pair(strName, strData)); //mapData[strName] = strData; } return 0; }
https://blog.csdn.net/wangshubo1989/article/details/52921285
引用:https://blog.csdn.net/jonathandj/article/details/4320725
最近正在研究C++下的XML分析工具CMarkup。初次和XML相遇是基於C#對XML的操作。C#的XmlDocument和XmlNode給我印象之深,讓我至今都無法忘懷。現在想在C++下發掘XML的強大,結果卻發現建房子你除了需要基本的建設材料外,還需要些而外的工具。不像C#那樣,已經打成包供你直接使用了。好在有知道CMarkup這個小型XML的分析器,可以為我所用。俗話說:磨刀不誤砍柴工。我現在就來磨下刀。
1、初始化
Load 導入一個XML文件到CMarkup的對象中,並對它進行解析。類似C#的Load。
SetDoc 從字符串中導入XML數據,並對它解析。類似C#的LoadXml。
2、輸出
Save 將XML數據寫入文件中。類似C#的Save。
GetDoc 將整個XML數據文檔作為字符串返回。
3、改變當前位置
FindElem 定位到下一個元素,可能和一個標簽名或路徑匹配。
FindChildElem 定位到下一個子元素,匹配元素名或路徑。
FindPrevElem 定位前一個元素,可能和一個標簽名或路徑匹配。
FindPrevChildElem 定位前一個子元素,可能匹配標簽名。
FindNode 定位下一個節點,可能和節點類型匹配。
IntoElem 進入當前主位置的下一級,當前的位置變為父位置。
OutOfElem 使當前父位置變成當前位置。
ResetPos 復位當前位置為文檔起始位置。
ResetMainPos 將當前主位置復位為第一個兄弟位置之前。
ResetChildPos 復位當前子位置到第一個子位置之前。
4、文檔新增
AddElem 在當前主位置元素或最后兄弟位置之后增加一個元素。
InsertElem 在當前主位置元素或第一個兄弟位置之前插入一個元素。
AddChildElem 在當前子位置元素或最后一個子位置之后增加一個元素。
InsertChileElem 在當前子位置元素或低一個子位置之前插入一個元素。
AddSubDoc 在當前主位置元素或最后一個兄弟位置之后增加一個子文檔。
InsertSubDoc 在當前主位置元素或第一個兄弟位置之前插入一個子文檔。
AddChildSubDoc 在當前子位置元素或最后一個子位置之后增加子文檔。
InsertChildSubDoc 在當前子位置元素或第一個子位置之前插入一個子文檔。
AddNode 在當前節點之后或父元素內容末尾增加一個節點。
InsertNode 在當前節點之前或父元素內容開頭插入一個節點。
5、文檔中刪除
RemoveElem 刪除當前包括子元素的主位置元素
RemoveChildElem 刪除包括當前子元素及其子元素
RemoveNode 刪除當前節點
RemoveAttrib 刪除當前位置元素具體的屬性
RemoveChildAttrib 刪除當前子位置元素的某個具體屬性
6、得到值
GetData 得到當前主位置元素或節點的字符串值
GetChildData 得到當前子位置元素的字符串值
GetElemContent 得到當前主位置元素包括其子元素的標記內容字符串值
GetSubDoc 得到當前主位置元素包括其子元素的文檔片斷標記字符串值
GetChildSubDoc 得到當前子位置元素包括其子元素的文檔片斷標記字符串值
GetAttrib 得到主位置元素(或正在進行的指令的)某一具體屬性字符串值
GetChildAttrib 得到子位置某一特定屬性的字符串值
GetTagName 得到主位置元素(或正在進行的指令的)標簽名稱
GetChildTagName 得到子位置元素的標簽名稱
FindGetData 定位到匹配某一具體路徑的下一個元素並返回字符串值
7、設置值
SetData 設置當前主位置元素或節點的值
SetChildData 設置當前子位置元素的值
SetElemContent 設置當前主位置元素的標記內容
SetAttrib 設置當前主位置元素(或正在進行的指令的)某一具體屬性的值
SetChildAttrib 設置當前子位置元素某一具體屬性的值
FindSetData 定位匹配某一具體路徑的下一個元素並設置其值
8、獲取其他信息
GetAttribName 當過當前位置元素屬性的具體索引得到屬性名稱
GetNodeType 得到當前節點的節點類型
GetElemLevel 得到當前主位置的級數
GetElemFlags 得到當前主位置元素的標志
SetElemFlags 設置當前主位置元素的標志
GetOffsets 獲得在當前主位置偏移的文檔文本
GetAttribOffsets 獲得在當前主位置特定屬性便宜的文檔文本
9、保存位置信息
SavePos 在hash map中使用可選字符串名稱保存當前位置
RestorePos 定位到通過SavePos保存的位置
SetMapSize 設置SavePos和RestorePos使用的hash map大小
GetElemIndex 得到當前主位置元素整形索引值
GotoElemIndex 設置當前主位置元素為給定的整形索引值
GetChildElemIndex 得到當前子位置元素的整形索引值
GotoChildElemIndex 設置當前子位置元素為給定的整形索引值
GetParentElemIndex 獲得當前父位置元素的整形索引值
GotoParentElemIndex 設置當前父位置元素為給定的整形索引值
GetElemPath 獲得表示主位置元素絕對路徑的字符串
GetChildElemPath 獲得表示子位置元素的絕對路徑的字符串
GetParentElemPath 獲得表示父位置元素的絕對路徑的字符串
10、文檔狀態
IsWellFormed 判定文檔是否有單一根元素和恰當地包含元素
GetError 從最后的解析中返回錯誤(信息)字符串
GetDocFlags 返回文檔標志
SetDocFlags 設置文檔標志
GetDocElemCount 返回文檔中元素的個數
11、靜態的實用函數
ReadTextFile 讀一個文本文件轉成字符串
WirteTextFile 寫字符串到文本文件中
GetDeclareEncoding 從XML聲明中得到編碼的名字
EscapeText 返回標記中某一字符的編碼
UnescapeText 返回字符串值得某一特定字符解碼
UTF8ToA 將UTF-8字符轉成非Unicode(如ANSI)字符
AToUTF8 將非Unicode(如ANSI)字符轉成UTF-8字符
UTF16T08 將UTF-16字符轉成UTF-8
UTF8To16 將UTF-8字符轉成UTF-16
EncodeBase64 將二進制數據譯成Base64字符串
DecodeBase64 將Base64字符譯成二進制數據
blog.csdn.net/weixin_33901926/article/details/89717752
Model
------------------------------------------------------------------------------------------
微軟的MSXML
使用方法:
#import "C:\\WINDOWS\\system32\\msxml6.dll"
//using namespace MSXML2;
例子:
xml是 <Book category="children"><title lang="en">Harry Potter</title><author>J.K. Rowling</author><year>2005</year><price>29.89</price></Book>
<Book category="children"> <title lang="en">Harry Potter</title> <author>J.K. Rowling</author> <year>2005</year> <price>29.89</price> </Book>

#import "C:\\WINDOWS\\system32\\msxml6.dll" //using namespace MSXML2; void CtestDialogDlg::OnOK() { {//創建xml文件 ::CoInitialize(NULL); //初始化COM MSXML2::IXMLDOMDocumentPtr pDoc; MSXML2::IXMLDOMElementPtr xmlRoot; HRESULT hr = pDoc.CreateInstance(__uuidof(MSXML2::DOMDocument30)); if (!SUCCEEDED(hr)) { MessageBox(L"XML文件創建失敗"); return; } pDoc->raw_createElement((_bstr_t)(char*)"Book", &xmlRoot); xmlRoot->setAttribute("category", "children"); pDoc->raw_appendChild(xmlRoot, NULL); MSXML2::IXMLDOMElementPtr pElemNode; pDoc->raw_createElement((_bstr_t)(char*)"title", &pElemNode); pElemNode->Puttext("Harry Potter"); pElemNode->setAttribute("lang", "en"); xmlRoot->appendChild(pElemNode); pDoc->raw_createElement((_bstr_t)(char*)"author", &pElemNode); pElemNode->Puttext("J.K. Rowling"); xmlRoot->appendChild(pElemNode); pDoc->raw_createElement((_bstr_t)(char*)"year", &pElemNode); pElemNode->Puttext("2005"); xmlRoot->appendChild(pElemNode); pDoc->raw_createElement((_bstr_t)(char*)"price", &pElemNode); pElemNode->Puttext("29.89"); xmlRoot->appendChild(pElemNode); pDoc->save(".\\test.xml");//保存到文件 //如何釋放pDoc占有的內存 ::CoUninitialize(); //卸載COM } {//讀取xml文件 ::CoInitialize(NULL); //初始化COM m_list.DeleteAllItems(); //m_list是ListControl控件綁定的一個Value類型的變量 MSXML2::IXMLDOMDocumentPtr pDoc; //創建一個xml文檔指針 HRESULT hr = pDoc.CreateInstance(__uuidof(MSXML2::DOMDocument30)); //實例化文檔指針 if (!SUCCEEDED(hr)) { MessageBox(L"加載XML錯誤"); return; } VARIANT_BOOL loadrs = pDoc->load(".\\test.xml"); //加載xml文檔 if (-1 != loadrs) //load返回類型是VARIANT_BOOL,-1 == TRUE、0 == FALSE MessageBox(L"加載XML錯誤"); MSXML2::IXMLDOMElementPtr pElemNode; //聲明一個元素(Element)指針 // 在樹中查找名為***的節點," // "表示在任意一層查找 //selectSingleNode方法如果查詢到一個或多個節點,返回第一個節點;如果沒有查詢的任何節點返回 Nothing //SelectNodes("//Book")返回一個NodeList對象,可能包含多個節點 pElemNode = (MSXML2::IXMLDOMElementPtr)(pDoc->selectSingleNode("//Book")); //獲取元素的信息 CString strValue = pElemNode->Gettext();//獲取Element標簽之間的Text文本,Puttext(LPCSTR)為設置Text文本 //注意:Book的text是“Harry PotterJ.K. Rowling200529.89” CString strAttr = pElemNode->getAttribute("category");//獲取元素的屬性,若無這個屬性拋異常 //遍歷子節點 MSXML2::IXMLDOMNodeListPtr nodeList = NULL; pElemNode->get_childNodes(&nodeList); //獲取所有子節點 long nCount = 0; nodeList->get_length(&nCount); MSXML2::IXMLDOMNodePtr pCurNode; for (int i = 0; i < nCount; ++i) { pCurNode = nodeList->nextNode(); CString strName = pCurNode->GetnodeName(); CString strValue = pCurNode->Gettext(); } { //查詢某個元素節點 MSXML2::IXMLDOMNodePtr pNode; pNode = pDoc->selectSingleNode("Book/price"); CString strValue = pNode->Gettext(); pNode = pDoc->selectSingleNode("Book/title/@lang");//屬性節點 CString strAttrName = pNode->GetnodeName();//lang CString strAttrVal = pNode->GetnodeValue();//en pNode = pDoc->selectSingleNode("Book/title"); strAttrVal = ((MSXML2::IXMLDOMElementPtr)pNode)->getAttribute("lang");//en } ::CoUninitialize(); //卸載COM }
若解析xml字符串,則:
const char* szXml = "<Book category=\"children\"><title lang=\"en\">Harry Potter</title><author>J.K. Rowling</author><year>2005</year><price>29.89</price></Book>"; VARIANT_BOOL loadrs = pDoc->loadXML(szXml);
參考:
https://blog.csdn.net/qq2399431200/article/details/17583171
https://blog.csdn.net/sky786905664/article/details/53696076
----------------------------------------------------------------------------------