2010. augusztus 31., kedd

XML DOM Parser in Delphi 6


Problem/Question/Abstract:

How to parse an XML File/String in Delphi?

Answer:

This is relevance to my previous article Importing XML DOM Parser Into Delphi....

In Delphi 6, there is a separate component to do the XML parsing in the Internet Palette, called TXMLDocument. With this component, we dont need to do any import like I mentioned in that article. The only thing you need is that you should have the relevant DLLs in your machine to do the parsing like MSXML.dll(Microsoft parser). You can use any parser as you wish.

Now let us quickly review the properties and methods of this component.

DOMVendor

It’s a drop-down list containing the parsers available in your machine. If you have MSXML.dll in your machine, then you will see MSXML in that drop-down list. It’s nothing but the Microsoft parser. Like that if you have other parsers, then those will also be listed there. You can choose one.

File Name or XML strings

You can either pass in a XML file or an XML string to that component.

XMLDocument1.FileName := 'sample.xml'
XMLDocument1.XML.strings.add('an xml string');

Once you set these two properties, you can set the Active property to true; this initiates the parsing. Any errors during parsing will be captured by the Delphi’s EDOMParseError exception.

Also, you can save the XML document or strings into a separate file or memory stream.

XMLDocument1.SaveToFile('File Name');
XMLDocument1.SaveToStream(MemoryStream);

Getting the XML Data

Once the XML has been parsed without any parsing errors, you can get node details by using the method getElementsByTagName and properties like NodeName, NodeValue, NodeType etc.,

As I mentioned in that article, the DTD file should be in the search path as the application or should be in the path where the exe resides. Also you have to make sure that the XML file or string you are parsing should follow the DTDs mentioned in that DTD file.

Nincsenek megjegyzések:

Megjegyzés küldése