XML in VC ++

zhaozj2021-02-16  48

By Richard Anderson

Introduction

The Extensible Markup Language (XML) is one of those technologies that you just know you should 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 Many Reasons? Suitability, Easy of Use, Availability of Tools, Media Coverage etc.

In this Article I'll Give You a Flying Start On How To Added 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 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 should have a basic understanding of XML concepts, specifically the structure of XML documents, 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 would 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 such as XML 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 thisime at 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........................................

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 does not 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 do not 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 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 is not anything new or exciting, you must remember to release all COM interface pointers before calling the later function. This may sound obvious, but you should 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 Scopeed To Ensure That It Is Destroyed Before The 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 Would Try And Release Its Contained Interface Pointer After COM IS Uninitialiad, Causeing 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 previously 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 on 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, Every Part 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 sprootel

SprootElement = SPMYFIRSTDocument-> CreateElement ("comDeveloper");

SpmyfirstDocument-> appendchild (rootElement);

In an XML document there can only ever be one root 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 (sylext);

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 create oor first XML Document Using IE5! Like I Said, It's Simple, Provided You've Got A Gooding 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-0000F87A7782

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 the 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 (), 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 Could Repesent this File Format As Follows:

We Could 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)>

]>

.................. ..

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;

Sylext = pParent-> OwnerDocument-> CreateTextNode (psztext);

PParent-> appendchild (sylext);}

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 addAndicleInfo (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 sprootel

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 (sprootel); addArticleInfo (SprootElement,

"SO, Why ATL? Why COM?",

"Dr. Richard Grimes",

"http://www.comdeveloper.com/articles/whytl.asp");

AddAnticleinfo (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 created a processing instruction node. 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 should consider from day one is that your applications when shipped will require 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 Secondors 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:

转载请注明原文地址:https://www.9cbs.com/read-28362.html

New Post(0)