VC++读取XML文件生成树

来源:互联网 发布:淘宝网 m.taobao.com 编辑:程序博客网 时间:2024/05/16 08:34
 
void CMonitorEmulationView::LoadTree()
{
    HTREEITEM CityTree,CompTree;
    
char path[256];
    memset(path,
0,256);
    GetModuleFileName(NULL,path,
256);
    
    LPCTSTR urf
="TreeXML.xml";
    strcat(p,urf);

    xml::IXMLDOMDocumentPtr pXMLDoc(__uuidof(xml::DOMDocument));

  
if(!PathFileExists(path))
        
return;
    
try
    
{
        pXMLDoc
->load(path);
    }


    
catch(_com_error& e)
    
{
        MessageBox(
"文件读取失败: " + e.Description(), "错误", MB_ICONWARNING);
           
return;
    }

    
 
    xml::IXMLDOMNodeListPtr pNodeList
=NULL;

    xml::IXMLDOMElementPtr spElement;
    HRESULT hr 
= pXMLDoc->get_documentElement(&spElement);   //获取根结点

    CComBSTR strTagName;

    hr 
= spElement->get_tagName(&strTagName);

    xml::IXMLDOMNodeListPtr spNodeList;

    hr 
= spElement->get_childNodes(&spNodeList);   //获取子结点列表

    
long lCount;                                       

    hr 
= spNodeList->get_length(&lCount);

    
for (long i=0; i<lCount; ++i)
    
{
        CComVariant varNodeValue;

        xml::IXMLDOMNodePtr spNode;
        xml::DOMNodeType NodeType;
        xml::IXMLDOMNodeListPtr spChildNodeList;
        hr 
= spNodeList->get_item(i, &spNode);         //获取结点
        hr = spNode->get_nodeType(&NodeType);     //获取结点信息的类型
        xml::IXMLDOMNamedNodeMapPtr pAttrs = NULL; 
        xml::IXMLDOMNodePtr pAttrItem;
        spNode
->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;
            CityTree
=m_wndTreeCtrl.InsertItem(_bstr_t(strAttrValue),userItem[0]);//父项1插入子项
        }



        
if (NODE_ELEMENT == NodeType)
        
{
            hr 
= spNode->get_childNodes(&spChildNodeList);
            
long childLen;
            hr 
= spChildNodeList->get_length(&childLen);
            
for (int j=0; j<childLen; ++j)
            
{
                xml::IXMLDOMNodePtr spChildNode;
                CComBSTR value;
                hr 
= spChildNodeList->get_item(j, &spChildNode);
                hr 
= spChildNode->get_nodeName(&value);            //获取结点名字
                hr = spChildNode->get_text(&value);                //获取结点的值
                
                CString strValue
=(char*)(_bstr_t)value;
                strValue.TrimRight();

                CompTree
=m_wndTreeCtrl.InsertItem((_bstr_t)strValue,CityTree);//父项1插入子项

                spChildNode.Release();
            }

        }

        spNode.Release();
        spChildNodeList.Release();
    }

    spNodeList.Release();
    spElement.Release();
    pXMLDoc.Release();
}
原创粉丝点击