1:#import "msxml4.dll" //加入导入库
2:AfxOleInit(); //初始化com组件
3:
void OnCreate()
{
// TODO: Add your control notification handler code here
MSXML2::IXMLDOMDocumentPtr pDoc;
MSXML2::IXMLDOMElementPtr xmlRoot ;
//创建DOMDocument对象
HRESULT hr = pDoc.CreateInstance(__uuidof(MSXML2::DOMDocument30));
if(!SUCCEEDED(hr))
{
MessageBox("无法创建DOMDocument对象,请检查是否安装了MS XML Parser 运行库!");
}
//根节点的名称为china
pDoc->raw_createElement((_bstr_t)(char*)"china", &xmlRoot);
pDoc->raw_appendChild(xmlRoot, NULL);
MSXML2::IXMLDOMElementPtr childNode ;
pDoc->raw_createElement((_bstr_t)(char*)"City", &childNode);
childNode->Puttext("WuHan");//节点值
childNode->setAttribute("population","8,000,000");//属性名,属性值
childNode->setAttribute("area","10000");
xmlRoot->appendChild(childNode);
pDoc->raw_createElement((_bstr_t)(char*)"City", &childNode);
childNode->Puttext("ShangHai");
childNode->setAttribute("population","12,000,000");
childNode->setAttribute("area","12000");
xmlRoot->appendChild(childNode);
//保存到文件
//如果不存在就建立,存在就覆盖
pDoc->save("he.xml");
}
void Load()
{
// TODO: Add your control notification handler code here
//创建DOMDocument对象
MSXML2::IXMLDOMDocumentPtr pDoc;
HRESULT hr = pDoc.CreateInstance(__uuidof(MSXML2::DOMDocument30));
if(!SUCCEEDED(hr))
{
MessageBox("无法创建DOMDocument对象,请检查是否安装了MS XML Parser 运行库!");
}
//加载文件
pDoc->load("he.xml");
//在树中查找名为City的节点,"//"表示在任意一层查找
MSXML2::IXMLDOMElementPtr childNode ;
childNode = (MSXML2::IXMLDOMElementPtr)(pDoc->selectSingleNode("//City[@population='8,000,000']");
//得到节点类型
MSXML2::DOMNodeType nodeType;
childNode->get_nodeType(&nodeType);
//节点名称
BSTR var;
CString name;
childNode->get_nodeName(&var);
name = (char*)(_bstr_t)var;
//节点值
VARIANT varVal;
childNode->get_nodeTypedValue(&varVal);
CString strValue = (char*)(_bstr_t)varVal;
//节点属性,放在链表中
MSXML2::IXMLDOMNamedNodeMapPtr pAttrs = NULL;
MSXML2::IXMLDOMNodePtr pAttrItem;
childNode->get_attributes(&pAttrs);
long nCount ;
pAttrs->get_length(&nCount);
for(int i = 0 ; i < nCount ; i++)
{
pAttrs->get_item(i,&pAttrItem);
//我们可以通过函数get_nodeName,get_nodeTypedValue得到属性名和属性值
//也可以直接得到
CString strAttrName = (char*)(_bstr_t)pAttrItem->nodeName;
CString strAttrValue = (char*)(_bstr_t)pAttrItem->nodeTypedValue;
}
}