Use XML in VC ++

Source: Internet
Author: User
Tags processing instruction

By Richard andresonintroduction

The Extensible Markup Language (XML) is one of those technologies that you just know you shoshould start supporting in your applications sooner rather than later. since it's official ratification in February 1998, it is fast becoming the de-facto way of exchanging and representing structured documents for each reasons? Suitability, easy of use, availability of tools, media coverage etc.

In this article I'll give you a flying start on how to add XML support to your application using the ie5 XML object model, in conjunction with the visual C ++ 6.0 Compiler? And (of course) COM.

In this first article I'll cover how to create a couple of XML documents ents from scratch. in subsequent articles I'll show you how to load and manipulate existing XML documents, as well as transforming XML documents into HTML (XHTML to be precise) by using the Extensible Stylesheet Language (XSL ).

To get the most from this article you shoshould have a basic understanding of XML concepts, specifically the structure of XML statements, and you also need to understand the basic concepts of the W3C Document Object Model (DOM), which is used to represent both XML and HTML documents in memory. I wowould love to introduce you to both of these standards, but this is only a short article. such detail is best left to another article, or books suchXML design and implementation(ISBN 1861002289 http://www.wrox.com/Books/Book_Details.asp? ISBN = 1861002289) published by wrox press.

The first sample we are going to write will produce an XML file that looks like this when viewed in ie5:

OK, I admit it, its nothing special or exciting, but the sample is very helpful in demonstrating some of the basic concepts about using the ie5 object model from C ++. it shows how to create an XML document object, and how DOM nodes are created and added to it. these nodes represent the comdeveloper element (represented by the start and end tags) and the 'hello xml' text shown in the picture.

Using the import directive

All the samples in this article use the # import directive to de-compile the ie5 Type Library into useable C ++ classes and smart pointers. this directive is part of what's known as the native com compiler support. I 've chosen to write the samples using this approach for several reasons. it is simple to use, helps to clearly demonstrate the usage of the ie5 objects without complicating the code, and ? Most importantly? It doesn't require you to go through the somewhat painful process of trying to get the latest SDK header files before you start.

Lets start by taking a look at the import directive that creates the C ++ Wrapper Classes for the ie5 object model:

#import "msxml.dll" rename_namespace("xml")

The most obvious point here is that the type library for ie5 is contained within MSXML. DLL. as this is located in the Windows System directory, I 've not had to specify a full path. the rename_namespace attribute defines all of the created Wrapper Classes in a C ++ namespace called XML. this is good because it prevents possible conflicts with existing include files you might have on your system, but does mean that everything must be prefixed with a namespace qualifier. so, for the interface ixmldomdocument (which will be discussed later) We have to explicitly specify the namespace like this: XML: ixmldomdocument. I personally quite like this syntax, But if you dislike namespaces or simply don't want to use them, try using the no_namespace attribute.


You can leave out the rename_namespace attribute, but you will have to prefix everything with MSXML.

The # import command gives us access to around 30 com interfaces and 5 classes. A lot of these are really legacy interfaces (from ie4), which have been kept to maintain compatibility, although they provide additional features not supported by some of the new interfaces. the ie5 interfaces that you shoshould be using all start with ixmldom. to help give you a feel for these interfaces, here is a UML dimo-showing the ixmldomxxx interfaces:

The list of interfaces is quite daunting at first, but it is actually a direct representation of the W3C DOM specification. microsoft has done a good job of implementing this specification in ie5. but, as usual, you will find that they have added additional methods and properties not in the W3C spec. OK, time to try out some of these interfaces.

Like any good com abiding application, each of our samples registers and de-registers from the com runtime using coinitialize and couninitialize. Whilst this isn't anything new or exciting, youMustRemember to releaseAllCOM interface pointers before calling the later function. this may sound obvious, but you shoshould remember that smart pointers only release their contained interface pointer when they're destroyed. so, if we look at the code from our sample that creates the XML document object, you will notice the smart pointer for the XML document is scoped to ensure that it is destroyedBeforeThe call to counitialize:

   CoInitialize(NULL);               // Register with COM   {      HRESULT hRes;      xml::IXMLDOMDocumentPtr spMyFirstDocument;      hRes = spMyFirstDocument.CreateInstance(__uuidof(xml::DOMDocument));      if(FAILED(hRes))      {         printf("Failed to create DOM document : %08x/n", hRes );         return 1;      }   }   CoUninitialize();                   // Unregister with COM

Without this scoping the smart pointer wocould try and release its contained interface pointer after com is uninitialised, causing our poor old sample app to crash.

As the code shows, creating a new XML document is pretty straightforward. the # import directive generates smart pointer types (such as ixmldomdocumentptr) for each interface in the ie5 Type Library, which we then use as shown above.

Looking at the code in a bit more detail, we see that an XML document object is created using the createinstance () method of the spmyfirstdocument smart pointer (SP ). we specify the com class to be created by using the rather nice _ uuidof keyword, which simply extracts the CLSID of the component to create. once the creation is completed, we have a reference-counted ixmldomdocument interface.


For those people that were previusly using the ie4 MSXML objects, note that the COM class to create is no longer xmldocument. that is still available, but I do not recommend using it because it is based upon an early working draft of the DOM specification.

The ixmldomdocument interface plays a pivotal role in the ie5 object model. it is the interface by which you can load and save existing documents, and more importantly for this first sample, it is the way in which DOM nodes for an XML document can be created. remember the W3C DOM specification,EveryPart of an XML document, including the document itself, is represented by a node.

Let's get on and actually create our XML document. first up, we create an element node by calling the createelement () method of ixmldomdocument. this takes the name of the element to create and returns a ixmldomtext interface, which represents a DOM text node. once again, a smart pointer looks after the returned interface. next, we take the returned element node and append it to the XML document using the appendchild () method:

   xml::IXMLDOMElementPtr spRootElement;   spRootElement = spMyFirstDocument->createElement("COMDeveloper");   spMyFirstDocument->appendChild(RootElement);

In an XML document there can only ever beOneRoot element. the first time you call appendchild () against a document node and pass in an element node, you are setting the root node. if you were to try and add another element node, you 'd find that an error is raised.

Next, we use the createtextnode () method to create a new text node containing "Hello XML ". we add this as a child node of the element by using the appendchild () method of the ixmldomtext interface:

   spSomeText = spMyFirstDocument->createTextNode("Hello XML");   spRootElement->appendChild(SomeText);


Appendchild () is actually defined in idomnode, so it's available to any interface that derives from this ..

Finally, we save our XML document to disk using the Save method:

MyFirstDocument->save("c://comdeveloper.xml");

That's it, we 've created our first XML document using ie5! Like I said, it's simple, provided you 've got a good grounding in XML and Dom.

The _ uuidof keyword provides a method of accessing the uuid/guid for a component or interface. For the domdocument component, the uuid is 3efaa428-272f-11d2-836f-440f87a7782

Sample 2-a slightly more complex XML file

In our next sample we will create a slightly more complex XML document, and look at common ways of helping to simplify the usage of the ie5 object model. starting with the output from the sample again, the generated XML file from this sample will look like this when viewed in ie5:

The document contains a partial list of articles that can be found on comdeveloper. each article is detailed within a child element node called article. this node contains three additional child text nodes (title, author and URL) which collectively describe the article and it's web location. you might also notice that this file has the standard XML Processing Instruction (<? XML version = "1.0"?> ), Which identifies the XML standard to which the document conforms. This instruction is also capable of saying whether the document is standalone and what it's encoding is.

For those people like me who are interested in UML modeling of XML schemas, We cocould represent this file format as follows:

 

We cocould also define the format using a document type definition (DTD) for the file like this:

>!DOCTYPE COMDeveloper_Articles [>!ELEMENT COMDeveloper_Articles (Article+)>>!ELEMENT Article               (Title,Author,URL) >>!ELEMENT Title                 (#PCDATA)>>!ELEMENT Author                (#PCDATA)>>!ELEMENT URL                   (#PCDATA)>]>


The zip file containing the sample code for this article has a sample that loads and validates an XML document against a DTD. It is located in the directory loadxml.

In this second sample we write a couple of semi re-usable helper functions, used to create the XML document. the first of these functions is called addtext (). this creates a text node containing the passed text, and appends it as a child node of the specified parent node:

void AddText(xml::IXMLDOMNode* pParent, const char* pszText){   xml::IXMLDOMTextPtr SomeText;   SomeText = pParent->ownerDocument->createTextNode(pszText);   pParent->appendChild(SomeText);}

The next helper method is called addarticleinfo (). this provides a way of creating all the DOM nodes (7 in total) that represent information about an article. it creates a new article element, and then creates and associates the sub-elements that contain the author, title and URL Information:

void AddArticleInfo(xml::IXMLDOMNode* pParent,                    const char* pszTitle,                    const char* pszAuthor,                    const char* pszURL){   xml::IXMLDOMElementPtr spArticle;   xml::IXMLDOMElementPtr spElement;   spArticle = pParent->ownerDocument->createElement("Article");   pParent->appendChild(spArticle);   spElement = pParent->ownerDocument->createElement("Title");   AddText(spElement, pszTitle);   spArticle->appendChild(spElement);   spElement = pParent->ownerDocument->createElement("Author");   AddText(spElement, pszAuthor);   spArticle->appendChild(spElement);   spElement = pParent->ownerDocument->createElement("URL");   AddText(spElement, pszURL);   spArticle->appendChild(spElement);   return;}

Using these two helper functions we can now create a more complex XML file in just a few lines of code:

int main(int argc, char* argv[]){   CoInitialize(NULL);               // Register with COM   {      HRESULT hRes;      xml::IXMLDOMDocumentPtr spArticlesDoc;      xml::IXMLDOMElementPtr spRootElement;      xml::IXMLDOMProcessingInstructionPtr spXMLPI;      spArticlesDoc.CreateInstance(__uuidof(xml::DOMDocument));      spXMLPI =         spArticlesDoc->createProcessingInstruction("xml","version=/"1.0/"");      spArticlesDoc->appendChild(spXMLPI);      spRootElement = spArticlesDoc->createElement("COMDeveloper_Articles");      spArticlesDoc->appendChild(spRootElement);      AddArticleInfo(spRootElement,                     "So, why ATL? why COM?",                     "Dr. Richard Grimes",                     "http://www.comdeveloper.com/articles/WhyATL.asp");      AddArticleInfo(spRootElement,                     "Attribute Programming",                     "Dr. Richard Grimes & Sing Li",                "http://www.comdeveloper.com/articles/attributeprogramming.asp");      spArticlesDoc->save( "c://comdeveloper.xml" );   }   CoUninitialize();                   // Unregister with COM   return 0;}

The only new aspect here, which I 've highlighted, is that I 've createdProcessing InstructionNode. As mentioned earlier, this specifies the XML version to which the document conforms. As this occurs at the same logical level as the root element, it is also added to the document node.

Well, that's about it for this article. hopefully I 've given you enough information and sample code to help jump-start your xml developments. one point that you shoshould consider from day one is that your applications when shippedWillRequire your clients to have ie5 installed. this is due to various DLL dependencies that Microsoft has promised to one day remove. if you don't want to have to ship ie5 or can't afford to wait for this separation, don't panic. other vendors do have XML support that you can use, some of which have almost identical interfaces to MSXML. I 've listed a couple of these in the reference section.

Some useful XML Resources

Here are some useful XML links:

The XML 1.0 specification:

Http://www.w3.org/TR/1998/REC-xml-19980210

Dom Level 1 specification:

Http://www.w3.org/TR/REC-DOM-Level-1/

General purpose XML site with links to dedicated useful resources:

Http://www.xmlsoftware.com

Microsoft:

Http://msdn.microsoft.com/xml/

Vivid creations-provide an MSXML style control that has the same basic xml dom interfaces but does not need ie5 to be installed:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.