TXMLDocument use case (C++)
From Code Examples
Language:
Description
This example illustrates the basic operations on an XML document.
Code
#include <vcl.h> #pragma hdrstop #include <tchar.h> #include <XMLDoc.hpp> #include <XMLIntf.hpp> #include <ComObj.hpp> #include <stdio.h> #pragma argsused void CreateDocument(); void RetrieveDocument(); int _tmain(int argc, _TCHAR* argv[]) { CoInitializeEx(NULL, 0); try { CreateDocument(); RetrieveDocument(); } catch (Exception &ex) { printf("Exception message: %ls\n", ex.Message); } return 0; } void CreateDocument() { const _TCHAR* filename = _TEXT("file.xml"); _di_IXMLDocument document = interface_cast<Xmlintf::IXMLDocument> (new TXMLDocument(NULL)); document->Active = true; // Define document content. document->DocumentElement = document->CreateNode("ThisIsTheDocumentElement", ntElement, ""); document->DocumentElement->Attributes["attrName"] = "attrValue"; _di_IXMLNode nodeElement = document->DocumentElement->AddChild ("ThisElementHasText", -1); nodeElement->Text = "Inner text."; _di_IXMLNode nodeCData = document->CreateNode("any characters here", ntCData, ""); document->DocumentElement->ChildNodes->Add(nodeCData); _di_IXMLNode nodeText = document->CreateNode("This is a text node.", ntText, ""); document->DocumentElement->ChildNodes->Add(nodeText); document->SaveToFile(filename); } void RetrieveDocument() { const _TCHAR* filename = _TEXT("file.xml"); const _di_IXMLDocument document = interface_cast<Xmlintf::IXMLDocument> (new TXMLDocument(NULL)); document->LoadFromFile(filename); // Find a specific node. const _di_IXMLNode nodeElement = document->ChildNodes->FindNode("ThisIsTheDocumentElement"); if (nodeElement != NULL) { // Get a specific attribute. puts("Getting attribute..."); const _TCHAR* attrName = _TEXT("attrName"); if (nodeElement->HasAttribute(attrName)) { const _TCHAR* attrValue = nodeElement->Attributes[attrName]; printf("Attribute value: %ls\n", attrValue); } // Traverse child nodes. puts("\nTraversing child nodes..."); for (int i = 0; i < nodeElement->ChildNodes->Count; i++) { const _di_IXMLNode node = nodeElement->ChildNodes->Get(i); // Display node name. printf("Node name: %ls\n", node->NodeName); // Check if the node type is Text. if (node->NodeType == ntText) { // Display node text. printf("\tThis is a node of type Text. The text is: %ls\n", node->Text); } // Check if the node is text element. if (node->IsTextElement) { printf("\tThis is a text element. The text is: %ls\n", node->Text); } } } }
Uses
- XMLDoc.TXMLDocument ( FR | DE | JP )