Last active
December 18, 2023 14:54
-
-
Save omonien/5770d5a83e40db3eaebb79b9ab53d86d to your computer and use it in GitHub Desktop.
Simple TXMLDocument Demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
program XmlDemo; | |
{$APPTYPE CONSOLE} | |
{$R *.res} | |
uses | |
Winapi.ActiveX, | |
System.Classes, System.SysUtils, System.IOUtils, | |
Xml.xmldom, | |
Xml.XMLDoc, | |
Xml.XMLIntf, | |
Xml.Win.msxmldom, | |
Xml.omnixmldom; | |
begin | |
try | |
// There are several DOM Vendors. | |
// MS is fastest | |
DefaultDOMVendor := SMSXML; | |
// Omni is slightly slower, but cross-platform | |
// DefaultDOMVendor := sOmniXmlVendor; | |
// Some plain Xml, stored in a file | |
// This is only to have a self-contained sample | |
// Note: THIS IS DELPHI 12 MULTI-LINE STRING SYNTAX | |
var LSampleXml := | |
''' | |
<?xml version="1.0" encoding="UTF-8" ?> | |
<note> | |
<to>Tove</to> | |
<from>Jani</from> | |
<heading>Reminder</heading> | |
<body>Don't forget me this weekend!</body> | |
</note> | |
'''; | |
// Save it to a file | |
TFile.WriteAllText('sample.xml', LSampleXml, Tencoding.UTF8); | |
// Now fire up a TxmlDocument | |
if DefaultDOMVendor = SMSXML then | |
begin | |
// CoInitialize every thread that uses MSXML | |
CoInitialize(nil); | |
end; | |
// Use IXMLDocument instead of TXMLDocument to keep your variable, otherwise you may get into trouble | |
var LXml: IXMLDocument := TXMLDocument.Create(nil); // You could pass in the file name here, but we will do it manually | |
LXml.LoadFromFile('sample.xml'); | |
Assert(LXml.Active); | |
Assert(LXml.Xml.Text.StartsWith('<?xml')); // Make sure "something" is loaded | |
// Now lets check for some of the expected nodes | |
var LRoot := LXml.DocumentElement; | |
Assert(LRoot.NodeName = 'note'); | |
Assert(LRoot.HasChildNodes); | |
var LBody := LRoot.ChildNodes['body']; | |
Assert(Assigned(LBody)); | |
Assert(LBody.NodeName = 'body'); | |
except | |
on E: Exception do | |
Writeln(E.ClassName, ': ', E.Message); | |
end; | |
end. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment