TXMLDocument use case (C++)
Description
The following 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();
const _TCHAR* destPath = _TEXT("../../dest.xml"); // File should exist.
const _TCHAR* srcPath = destPath;
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() {
_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(destPath);
}
void RetrieveDocument() {
const _di_IXMLDocument document = interface_cast<Xmlintf::IXMLDocument>
(new TXMLDocument(NULL));
document->LoadFromFile(srcPath);
// 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 whether 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 whether the node is a text element.
if (node->IsTextElement) {
printf("\tThis is a text element. The text is: %ls\n",
node->Text);
}
}
}
}
Uses
- Xml.XMLDoc.TXMLDocument.Active ( fr | de | ja )
- Xml.XMLDoc.TXMLDocument.AddChild ( fr | de | ja )
- Xml.XMLDoc.TXMLDocument.CreateNode ( fr | de | ja )
- Xml.XMLDoc.TXMLDocument.SaveToFile ( fr | de | ja )
- Xml.XMLDoc.TXMLDocument.LoadFromFile ( fr | de | ja )
- Xml.XMLIntf.IXMLNodeList.FindNode ( fr | de | ja )
- Xml.XMLDoc.TXMLNode.ChildNodes ( fr | de | ja )
- Xml.XMLDoc.TXMLNode.HasAttribute ( fr | de | ja )
- Xml.XMLIntf.IXMLNode.Attributes ( fr | de | ja )