Reputation: 53
Here is the thing I want to do. My program is working fine with this:
XMLText = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
'<book xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">' +
'<title>Harry Potter</title>' +
'<author>J. K. Rowling.</author>' +
'<length>400</length>' +
'</book>';
procedure TForm1.Button1Click(Sender: TObject);
var
XMLDoc: IXMLDOMDocument;
Node, SibNode: IXMLDOMNode;
begin
Memo1.Clear;
XMLDoc := CoDOMDocument.Create;
XMLDoc.loadXML(XMLText);
end;
Now I want to import XML file with 6000 books (books.xml) from the same folder where project is, instead of const XMLText. How can I do that?
Thank you! :)
Upvotes: 1
Views: 17841
Reputation: 24523
Use the Delphi XML Data Binding Wizard for this.
It will generate a unit with Delphi wrapper objects around your XML file (or if you have it an XSD file describing the XML).
Those wrappers are based on the IXMLDocument
which is very similar to the IXMLDOMDocument
you are using now, and add a layer around it that allows you to access your data with more support from the Delphi compiler usually making the process of handling the data inside the XML much easier than using plain IXMLDocument
or IXMLDOMDocument
.
The unit contains methods to load the XML from either a file or a string.
There is a good tutorial and a nice video on using this wizard.
Upvotes: 4
Reputation: 125749
Just change the loadXML
to load('YourFileName.xml')
:
procedure TForm1.Button1Click(Sender: TObject);
var
XMLDoc: IXMLDOMDocument;
begin
XMLDoc := CoDOMDocument.Create;
XMLDoc.load('MyBooks.xml');
Memo1.Lines.Text := XMLDoc.xml;
end;
Upvotes: 3
Reputation: 116160
Option 1: load directly from disk
IXMLDomDocument
has a load
method that accepts a filename. You can use that method instead of loadXML
, which you are currently using.
Option 2: load the file into a string first
Alternatively, you can load your file into a string first. I can hardly find any reason to do so in this case, but it can never hurt to know. :)
Take a look at TStringStream
, which has a LoadFromFile
method to load a file from disk. You can use it to load the entire books.xml
into memory. After loading the file, you can pass the stringstreams's DataString
property to the loadXML
method. This property returns the entire contents of the stream (containing the XML) as a string.
Upvotes: 6