XML DOM Objects/Interfaces

10 篇文章
这篇博客详细介绍了XML DOM中的核心对象和接口,包括IXMLDOMAttribute、IXMLDOMDocument、IXMLDOMElement、IXMLDOMNamedNodeMap、IXMLDOMNode、IXMLDOMNodeList和IXMLDOMSelection。通过示例代码展示了如何使用这些接口操作XML文档,如创建、查询和修改元素、属性等。最后,还给出了输出示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

IXMLDOMAttribute 
Represents an attribute of the IXMLDOMElement. Valid and default values for the attribute are defined in a document type definition (DTD) or schema.

Example
The following example is in C++.

#import  " msxml3.dll "
using   namespace  MSXML2;

#define  CHECK_AND_RELEASE(pInterface)  
if (pInterface) 
{
   pInterface
-> Release();
   pInterface 
=  NULL;
}

#define  RELEASE(pInterface)  
{
   pInterface
-> Release();
   pInterface 
=  NULL;
}

int  main( int  argc,  char *  argv[])
{
   _variant_t varValue;
   BSTR bstrAttributeName 
=  ::SysAllocString(_T( " dateCreated " ));
   IXMLDOMAttribute 
* pIXMLDOMAttribute  =  NULL;
   IXMLDOMElement 
* pIXMLDOMElement  =  NULL;
   IXMLDOMDocument 
* pIXMLDOMDocument  =  NULL;
   HRESULT hr;
   
   
try
   {
      
//  Initialize pIXMLDOMDocument and load an
      
//  XML file into it.
      
//  Get the document root.
      hr  =  pIXMLDOMDocument -> get_documentElement(  & pIXMLDOMElement);
      SUCCEEDED(hr) 
?   0  :  throw  hr;
      
if (pIXMLDOMElement)
      {
         varValue 
=  _T( " Year 2000 " );
   
         
//  Set the "dateCreated" attribute to "year 2000"
         hr  =  pIXMLDOMElement -> setAttribute(bstrAttributeName, varValue);
         SUCCEEDED(hr) 
?   0  :  throw  hr;
   
         
//  Retrieve the changed attribute.
         hr  =  pIXMLDOMElement -> getAttributeNode(bstrAttributeName,
                                                
& pIXMLDOMAttribute);
         SUCCEEDED(hr) 
?   0  :  throw  hr;
   
         pIXMLDOMAttribute
-> get_nodeValue( & varValue);
         
         
if (varValue.vt  !=  VT_NULL)
         {
            
//  Display the retrieved attribute in a message box.
            ::MessageBox(NULL, _bstr_t(varValue), bstrAttributeName, MB_OK);
         }
         RELEASE(pIXMLDOMElement);
          RELEASE(pIXMLDOMAttribute);
      }
      ::SysFreeString(bstrAttributeName);
      bstrAttributeName
= NULL;
   }
   
catch (...)
   {
      
if (bstrAttributeName)
      {
         ::SysFreeString(bstrAttributeName);
         bstrAttributeName 
=  NULL;
      }
      CHECK_AND_RELEASE(pIXMLDOMElement);
      
//    DisplayErrorToUser();
   }
   
//  Release pIXMLDOMDocument when finished with it.
    return   0 ;
}

 

IXMLDOMDocument/DOMDocument 
Represents the top level of the XML source. Includes members for retrieving and creating all other XML objects.

Example
The following C/C++ example creates DOMDocument and queries for the other interfaces.

HRESULT hr;
IXMLDOMDocument 
*  pXMLDoc;
IXMLDOMNode 
*  pXDN;
// ...
hr  =  CoInitialize(NULL); 
//  Check the return value, hr...
hr  =  CoCreateInstance(CLSID_DOMDocument30, NULL, CLSCTX_INPROC_SERVER, 
       IID_IXMLDOMDocument, (
void ** ) & pXMLDoc);
//  Check the return value, hr...
hr  =  pXMLDoc -> QueryInterface(IID_IXMLDOMNode, ( void   ** ) & pXDN);
//  Check the return value.

 

IXMLDOMElement 
Represents the element object.

Example
The following C/C++ example displays the entire sample XML file (Books.xml) from its document element.

#import  " msxml3.dll "
using   namespace  MSXML2;

inline 
void  TESTHR( HRESULT _hr ) 
   { 
if  FAILED(_hr)  throw (_hr); }

void  XMLDOMElementSample()
{
    
try  {
        IXMLDOMDocumentPtr docPtr;
        IXMLDOMElementPtr ElementPtr;

        
// init
        TESTHR(CoInitialize(NULL)); 
        TESTHR(docPtr.CreateInstance(
" Msxml2.DOMDocument.3.0 " ));

        
//  Load a document.
        _variant_t varXml( " books.xml " );
        _variant_t varOut((
bool )TRUE);
        varOut 
=  docPtr -> load(varXml);
        
if  (( bool )varOut  ==  FALSE)
            
throw ( 0 );
        ElementPtr 
=  docPtr -> documentElement;
        MessageBox(NULL, ElementPtr
-> xml, _T( " Document from its root " ), MB_OK);
    } 
catch (...)
    {
        MessageBox(NULL, _T(
" Exception occurred " ), _T( " Error " ), MB_OK);
    }
    CoUninitialize();
}

 

IXMLDOMNamedNodeMap 
Adds support for namespaces and iteration through the collection of attribute nodes.

Example
The following C/C++ example creates and appends a new attribute to the root document element.

#import  " msxml3.dll "
using   namespace  MSXML2;

inline 
void  TESTHR( HRESULT _hr ) 
   { 
if  FAILED(_hr)  throw (_hr); }

void  XMLDOMNamedNodeMap()
{
    
try  {
        IXMLDOMDocumentPtr docPtr;
        IXMLDOMNodePtr DOMNodePtr;
        IXMLDOMNamedNodeMapPtr DOMNamedNodeMapPtr;

        
// init
        TESTHR(CoInitialize(NULL)); 
        TESTHR(docPtr.CreateInstance(
" Msxml2.DOMDocument.5.0 " ));
        
        VARIANT vtTemp;

        vtTemp.vt
= VT_I2;
        vtTemp.iVal 
=  MSXML2::NODE_ATTRIBUTE;

        
//  load a document
        _variant_t varXml( " C:/book.xml " );
        _variant_t varOut((
bool )TRUE);
        varOut 
=  docPtr -> load(varXml);
        
if  (( bool )varOut  ==  FALSE)
            
throw ( 0 );
        
        DOMNodePtr 
=  docPtr -> createNode(vtTemp,  " Sci-Fi " "" );
        DOMNamedNodeMapPtr 
=  docPtr -> documentElement -> attributes;
        DOMNamedNodeMapPtr
-> setNamedItem(DOMNodePtr);

        MessageBox(NULL, _bstr_t(docPtr
-> xml), _T( " New Document " ), MB_OK);

    } 
catch (...)
    {
        MessageBox(NULL, _T(
" Exception occurred " ), _T( " Error " ), MB_OK);
    }
    CoUninitialize();
}

 

IXMLDOMNode 
Extends the core node with support for data types, namespaces, document type definitions (DTDs), and schemas.

Example
The following C/C++ example creates and appends a new node to the document root.

#include  < tchar.h >
#import 
" msxml5.dll "
using   namespace  MSXML2;

inline 
void  TESTHR( HRESULT _hr ) 
   { 
if  FAILED(_hr)  throw (_hr); }

void  XMLDOMNodeSample()
{
    
try  {
        IXMLDOMDocumentPtr docPtr;
        IXMLDOMNodePtr DOMNodePtr;

        
// init
        TESTHR(CoInitialize(NULL)); 
        TESTHR(docPtr.CreateInstance(
" Msxml2.DOMDocument.5.0 " ));
        
        VARIANT vtTemp;

        vtTemp.vt
= VT_I2;
            vtTemp.iVal 
=   1 // NODE_ELEMENT
        
//  load a document
        _variant_t varXml( " c:/Temp/books.xml " );
        _variant_t varOut((
bool )TRUE);
        varOut 
=  docPtr -> load(varXml);
        
if  (( bool )varOut  ==  FALSE)
            
throw ( 0 );
        MessageBox(NULL, _bstr_t(docPtr
-> xml), _T( " Original Document " ), MB_OK);
        DOMNodePtr 
=  docPtr -> createNode(vtTemp,  " VIDEOS " "" );
        docPtr
-> documentElement -> appendChild(DOMNodePtr);
        MessageBox(NULL, _bstr_t(docPtr
-> xml), _T( " New Document " ), MB_OK);

    } 
catch (...)
    {
        MessageBox(NULL, _T(
" Exception occurred " ), _T( " Error " ), MB_OK);
    }
    CoUninitialize();
}
int  main()
{
    XMLDOMNodeSample();
    
return   0 ;
}

 

IXMLDOMNodeList 
Supports iteration through the live collection, in addition to indexed access.

Example
The following C/C++ example gets all elements with node name AUTHOR and displays the number of nodes found with the following sample.

<? xml version = ' 1.0 ' ?>
< COLLECTION
   xmlns:dt
= " urn:schemas-microsoft-com:datatypes " >
  
< DATE dt:dt = " datetime " > 1998 - 10 - 13T15: 56 : 00 </ DATE >
  
< BOOK >
    
< TITLE > Lover Birds </ TITLE >
    
< AUTHOR > Cynthia Randall </ AUTHOR >
    
< PUBLISHER > Lucerne Publishing </ PUBLISHER >
  
</ BOOK >
  
< BOOK >
    
< TITLE > The Sundered Grail </ TITLE >
    
< AUTHOR > Eva Corets </ AUTHOR >
    
< PUBLISHER > Lucerne Publishing </ PUBLISHER >
  
</ BOOK >
  
< BOOK >
    
< TITLE > Splish Splash </ TITLE >
    
< AUTHOR > Paula Thurman </ AUTHOR >
    
< PUBLISHER > Scootney </ PUBLISHER >
  
</ BOOK >
</ COLLECTION >

#import 
" msxml3.dll "
using   namespace  MSXML2;

inline 
void  TESTHR( HRESULT _hr ) 
   { 
if  FAILED(_hr)  throw (_hr); }

void  XMLDOMNodeListSample()
{
    
try  {
        IXMLDOMDocumentPtr docPtr;
        IXMLDOMNodeListPtr NodeListPtr;
        IXMLDOMNodePtr DOMNodePtr;

        
// init
        TESTHR(CoInitialize(NULL)); 
        TESTHR(docPtr.CreateInstance(
" Msxml2.DOMDocument.5.0 " ));

        
//  load a document
        _variant_t varXml( " C:/book.xml " );
        _variant_t varOut((
bool )TRUE);
        varOut 
=  docPtr -> load(varXml);
        
if  (( bool )varOut  ==  FALSE)
            
throw ( 0 );
        NodeListPtr 
=  docPtr -> getElementsByTagName( " AUTHOR " );
        MessageBox(NULL, _bstr_t(NodeListPtr
-> length), _T( " Node List length " ), MB_OK);
    } 
catch (...)
    {
        MessageBox(NULL, _T(
" Exception occurred " ), _T( " Error " ), MB_OK);
    }
    CoUninitialize();
}

 

IXMLDOMSelection 
Represents the list of nodes that match a given XML Path Language (XPath) expression.

Example
In the following C/C++ example, IXMLDOMSelection inherits the threading model of the document that created it. IXMLDOMSelection is created through the selectNodes method on IXMLDOMDocument2.

<? xml version = ' 1.0 ' ?>
< COLLECTION xmlns:dt = " urn:schemas-microsoft-com:datatypes " >
  
< DATE dt:dt = " datetime " > 1998 - 10 - 13T15: 56 : 00 </ DATE >
  
< BOOK >
    
< TITLE > Lover Birds </ TITLE >
    
< AUTHOR > Cynthia Randall </ AUTHOR >
    
< PUBLISHER > Lucerne Publishing </ PUBLISHER >
 
</ BOOK >
 
< BOOK >
    
< TITLE > The Sundered Grail </ TITLE >
    
< AUTHOR > Eva Corets </ AUTHOR >
    
< PUBLISHER > Lucerne Publishing </ PUBLISHER >
 
</ BOOK >
 
< BOOK >
    
< TITLE > Splish Splash </ TITLE >
    
< AUTHOR > Paula Thurman </ AUTHOR >
    
< PUBLISHER > Scootney </ PUBLISHER >
 
</ BOOK >
</ COLLECTION >


#import 
" msxml3.dll "
using   namespace  MSXML2;

#define  CHECK_AND_RELEASE(pInterface)  
if (pInterface) 
   {
pInterface
-> Release();
pInterface 
=  NULL;
   }

#define  RELEASE(pInterface)  
   {
pInterface
-> Release();
pInterface 
=  NULL;
   }

BOOL DOMSelectionDemo()
{
   BOOL bResult 
=  FALSE;
   
short  sResult  =  FALSE;
   IXMLDOMSelection 
* pIXMLDOMSelection = NULL;
   IXMLDOMNodeList 
* pIXMLDOMNodeList = NULL;
   IXMLDOMNode 
* pIXMLDOMNode = NULL;
   IXMLDOMDocument2 
* pIXMLDOMDocument2 = NULL;
   BSTR bstrValue;
   HRESULT hr;

   
try
   {
      hr
= CoCreateInstance(CLSID_DOMDocument, NULL, CLSCTX_SERVER,
               IID_IXMLDOMDocument2, (LPVOID
* )( & pIXMLDOMDocument2));
      SUCCEEDED(hr) 
?   0  :  throw  hr;

      
if (pIXMLDOMDocument2)
      {
         hr
= pIXMLDOMDocument2 -> put_async(VARIANT_FALSE);
         
if (SUCCEEDED(hr))
         {
            hr
= pIXMLDOMDocument2 -> load(_variant_t( 
      _T(
" samplexmldtd.xml " )),  & sResult);
            
if (SUCCEEDED(hr)  &&  (sResult == VARIANT_TRUE))
            {
               hr
= pIXMLDOMDocument2 -> selectNodes( 
               _T(
" */BOOK[TITLE='Lover Birds'] " ),  & pIXMLDOMNodeList);
               
if (SUCCEEDED(hr))
               {
                  hr
= pIXMLDOMNodeList -> QueryInterface(IID_IXMLDOMSelection
                     ,(
void ** ) & pIXMLDOMSelection );
                  
if (SUCCEEDED(hr)  &&  pIXMLDOMSelection)
                  {
                     LONG uLength;

                     bResult
= TRUE;
                     hr
= pIXMLDOMSelection -> get_length( & uLength);
                     
if (SUCCEEDED(hr))
                     {
                        
for ( int  iIndex = 0 ; iIndex  <  uLength; iIndex ++ )
                        {
                           
//  remove all the nodes from the list-display 
                           
//  them as they are removed.
                           hr = pIXMLDOMSelection -> removeNext(
                              
& pIXMLDOMNode);
                           
if (SUCCEEDED(hr)  &&  pIXMLDOMNode)
                           {   
                              hr
= pIXMLDOMNode -> get_text( & bstrValue);
                              
if (SUCCEEDED(hr))
                                 ::MessageBox(NULL, bstrValue, _T(
" Node
                                  Text " ), MB_OK);
                              RELEASE(pIXMLDOMNode);
                           }
                        }
                     }
                     RELEASE(pIXMLDOMSelection);
                  }
                  RELEASE(pIXMLDOMNodeList);
               }
            }
         }
         RELEASE(pIXMLDOMDocument2);
      }
   }
   
catch (...)
   {
      CHECK_AND_RELEASE(pIXMLDOMNode);
      CHECK_AND_RELEASE(pIXMLDOMDocument2);
      CHECK_AND_RELEASE(pIXMLDOMNodeList);
      CHECK_AND_RELEASE(pIXMLDOMSelection);
      DisplayErrorToUser();
   }
   
return  bResult;
}

Output

The example outputs the following in a message box.

Lover Birds Cynthia Randall Lucerne Publishing

 

IXMLDOMText 
Represents the text content of an element or attribute.

Example
The following C/C++ example creates and appends a new text node to the root document element.

#import  " msxml3.dll "
using   namespace  MSXML2;

inline 
void  TESTHR( HRESULT _hr ) 
   { 
if  FAILED(_hr)  throw (_hr); }


void  XMLDOMText()
{
   
try  {
      IXMLDOMDocumentPtr docPtr;
      IXMLDOMNodePtr DOMNodePtr;
      IXMLDOMNamedNodeMapPtr DOMNamedNodeMapPtr;

      
// init
      TESTHR(CoInitialize(NULL)); 
      TESTHR(docPtr.CreateInstance(
" Msxml2.DOMDocument.3.0 " ));
      
      
//  load a document
      _variant_t varXml( " <root><child/></root> " );
      _variant_t varOut((
bool )TRUE);
      varOut 
=  docPtr -> loadXML(varXml);
      
if  (( bool )varOut  ==  FALSE)
         
throw ( 0 );
      
      DOMNodePtr 
=  docPtr -> createTextNode( " Hello World! " );

      docPtr
-> documentElement -> appendChild(DOMNodePtr);

      MessageBox(NULL, _bstr_t(docPtr
-> xml), _T( " New Document " ), MB_OK);

   } 
catch (...)
   {
      MessageBox(NULL, _T(
" Exception occurred " ), _T( " Error " ), MB_OK);
   }
   CoUninitialize();
}

Output

<root>Hello World!<child/></root>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值