VC_XML
二,初始化OLE.
BOOL CXmlApp::InitInstance()
{
AfxOleInit();
…….
}
三, 在对话框中增加一个按钮,ID为IDC_CREATE,我们在这个按钮的响应函数中生成一个xml文件.
void CXmlDlg::OnCreate()
{
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("f:""he.xml");
}
不要忘了#import "msxml4.dll"//引入类型库
四, 再增加一个按钮,ID为IDC_GET,在这个按钮的响应函数中读取xml文件.
void CXmlDlg::OnGet()
{
//创建DOMDocument对象
MSXML2::IXMLDOMDocumentPtr pDoc;
HRESULT hr = pDoc.CreateInstance(__uuidof(MSXML2::DOMDocument30));
if(!SUCCEEDED(hr))
{
MessageBox("无法创建DOMDocument对象,请检查是否安装了MS XML Parser 运行库!");
}
//加载文件
pDoc->load("f:""he.xml");
//在树中查找名为City的节点,"//"表示在任意一层查找
MSXML2::IXMLDOMElementPtr childNode ;
childNode = (MSXML2::IXMLDOMElementPtr)(pDoc->selectSingleNode("//City"));
//得到节点类型
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;
}
}
更多技术文章请参看施昌权的个人网站: http://www.joyvc.cn