分类: C/C++
2008-02-29 16:19:53
#import "msxml4.dll" //引入类型库(这个别忘了)
void CXmltestDlg::OnCreate()
{
MSXML2::IXMLDOMDocumentPtr pDoc;
MSXML2::IXMLDOMElementPtr xmlRoot;
//创建DOMDocument对象
HRESULT hr = pDoc.CreateInstance(__uuidof(MSXML2::DOMDocument30));
if(!SUCCEEDED(hr))
{
MessageBox("无法创建DOMDocument对象,请检查是否安装了MS XML Parser 运行库!");
return;
}
//根节点的名称为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->raw_createElement((_bstr_t)(char*)"City", &childNode);
childNode->Puttext("ChengDu");
childNode->setAttribute("population","13,000,000");
childNode->setAttribute("area","15000");
xmlRoot->appendChild(childNode);
//保存到文件
//如果不存在就建立,存在就覆盖
pDoc->save("d:\\he.xml");
}
//以下是得到XML的结点名称和属性(我搜索到的网上的例子只能得到第一个结点,改写的如下)
void CXmltestDlg::OnGet()
{
//创建DOMDocument对象
MSXML2::IXMLDOMDocumentPtr pDoc;
HRESULT hr = pDoc.CreateInstance(__uuidof(MSXML2::DOMDocument30));
if(!SUCCEEDED(hr))
{
MessageBox("无法创建DOMDocument对象,请检查是否安装了MS XML Parser 运行库!");
return;
}
//加载文件
pDoc->load("d://he.xml");
CString str1;
MSXML2::IXMLDOMElementPtr childNode ;
// MSXML2::IXMLDOMNodePtr node;
// node = (MSXML2::IXMLDOMNodePtr)(pDoc->GetparentNode());
MSXML2::IXMLDOMNamedNodeMapPtr pAttrs = NULL;
MSXML2::IXMLDOMNodePtr pAttrItem;
long nCount ;
for (int j = 0 ;j < 3;j++)
{
str1.Format("//City[%d]",j);
//在树中查找名为City的节点,"//"表示在任意一层查找
childNode = (MSXML2::IXMLDOMElementPtr)(pDoc->selectSingleNode((_bstr_t)str1));
//得到节点类型
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;
//节点属性,放在链表中
childNode->get_attributes(&pAttrs);
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;
CString temp;
temp.Format("%s\t%s\t%s",strValue,strAttrName,strAttrValue);
AfxMessageBox(temp);
}
}
}