0
回答
vc读写xml
注册华为云得mate10,2.9折抢先购!>>>   

今天对XML文件进行了一些简单的读写操作,下面来具体实现步骤:

首先:建立一个基于Dialog的MFC工程,工程名为OperateXML,然后在对话框上添加两个按钮("Create"和"GetData"和一个ListControl
控件(用来显示数据),首先要导入库文件
#import "msxml3.dll"
using namespace MSXML2;
主要用来实现XML文件的相关操作,
双击"Create"按钮进入代码编写,代码如下:
void COperateXML::OnBtnCreate()
{
// TODO: Add your control notification handler code here
::CoInitialize(NULL); //初始化COM
MSXML2::IXMLDOMDocumentPtr pDoc;
MSXML2::IXMLDOMElementPtr xmlRoot;
HRESULT hr = pDoc.CreateInstance(__uuidof(MSXML2::DOMDocument30));
if(!SUCCEEDED(hr))
{
   MessageBox("Error");
   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("shanghai");
childNode->setAttribute("population", "7000");
childNode->setAttribute("area", "2000");
xmlRoot->appendChild(childNode);

pDoc->raw_createElement((_bstr_t)(char*)"city", &childNode);
childNode->Puttext("beijing");
childNode->setAttribute("population", "39999");
childNode->setAttribute("area", "3322");
xmlRoot->appendChild(childNode);

pDoc->save("D:\\test.xml");
}

双击"GetData"按钮进入代码编写,代码如下:
void COperateXML::OnBtnGet()
{
// TODO: Add your control notification handler code here
m_list.DeleteAllItems();
MSXML2::IXMLDOMDocumentPtr pDoc;
HRESULT hr = pDoc.CreateInstance(__uuidof(MSXML2::DOMDocument30));
if(!SUCCEEDED(hr))
{
   MessageBox("Error!");
   return;
}
pDoc->load("D:\\test.xml");
MSXML2::IXMLDOMElementPtr childNode;
childNode = (MSXML2::IXMLDOMElementPtr)(pDoc->selectSingleNode("//city"));

MSXML2::DOMNodeType nodeType;
childNode->get_nodeType(&nodeType);

MSXML2::IXMLDOMNamedNodeMapPtr pAttrs = NULL;
MSXML2::IXMLDOMNodeListPtr nodeList;
MSXML2::IXMLDOMNodePtr pAttrItem;
childNode->get_attributes(&pAttrs);
childNode->get_childNodes(&nodeList);
long nCount, iCount;
pAttrs->get_length(&nCount); //获取节点属性个数
nodeList->get_length(&iCount); //获取节点个数
for(int i = 0; i < iCount; i++) //根据需要可以添加数据到ListControl中
{
   for(int j = 0; j < nCount; j++)
   {
    pAttrs->get_item(j, &pAttrItem);
    CString strAttrName = (char*)(_bstr_t)pAttrItem->nodeName;
    CString strAttrValue = (char*)(_bstr_t)pAttrItem->nodeTypedValue;
    m_list.InsertItem(i, strAttrName);
    m_list.SetItemText(i, 1, strAttrValue);
   }
}

}

为ListControl控件绑定一个操作变量

CListCtrl m_list;

在OnInitDialog中初始化,代码如下:

BOOL COperateXML::OnInitDialog()
{
// TODO: Add extra initialization here
m_list.InsertColumn(0, "人口");
m_list.InsertColumn(1, "Num");
m_list.InsertColumn(1, "面积");
m_list.InsertColumn(1, "Num");
CRect rect;
m_list.GetClientRect(&rect);
int width = (rect.right - rect.left) / 4;
m_list.SetColumnWidth(0, width);
m_list.SetColumnWidth(1, width);
m_list.SetColumnWidth(2, width);
m_list.SetColumnWidth(3, width);
}

F7编译程序,Ctrl+F5查看显示结果,至此一个简单的操作XML文件的实现已经成功的完成了。

转自:http://www.cnblogs.com/scq2099yt/archive/2008/01/29/1057704.html

<无标签>
举报
长平狐
发帖于6年前 0回/112阅
顶部