如何用VC读取xml文件中的信息,谁给个例子或者资料?

snake1122 2004-04-01 04:08:37
刚接到任务,有点一筹莫展,要求用msxml4.0读入,只能使用DOM方法,那位大虾做过?给点例子或者这方面的资料,谢谢!
...全文
124 点赞 收藏 3
写回复
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
snake1122 2004-04-01
请大家继续补充,测试成功立马回来结贴
回复
snake1122 2004-04-01
谢谢楼上兄台
回复
jinxuliang 2004-04-01
//生成一个xml文件
void CXMLDlg::OnCreateXml()
{
// TODO: Add your control notification handler code here
::CoInitialize(NULL);
MSXML2::IXMLDOMDocumentPtr pDoc;
MSXML2::IXMLDOMElementPtr xmlRoot;
//创建DOMDOCUMENT对象
HRESULT hr=pDoc.CreateInstance(_uuidof(MSXML2::DOMDocument40));
if(!SUCCEEDED(hr))

{

MessageBox("无法创建DOMDocument对象,请检查是否安装了MS XML Parser 运行库!");
return ;

}
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("e:\\he.xml");

}


//解析一个xml文件
void CXMLDlg::OnPharseXml()
{
// TODO: Add your control notification handler code here
MSXML2::IXMLDOMDocumentPtr pDoc;

HRESULT hr = pDoc.CreateInstance(__uuidof(MSXML2::DOMDocument40));

if(!SUCCEEDED(hr))

{

MessageBox("无法创建DOMDocument对象,请检查是否安装了MS XML Parser 运行库!");
return ;

}

//加载文件

pDoc->load("e:\\he.xml");

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;

}





}
回复
发动态
发帖子
VC/MFC
创建于2007-09-28

1.5w+

社区成员

VC/MFC相关问题讨论
申请成为版主
社区公告
暂无公告