问题
I am looking for some actual working sample code to read an XML using the plain OmniXml (or OmniXmlUtils) unit. I don't want to use the TOmniXMLWriter class , as explained elsewhere , but want to load an xml file using plain Delphi code.
I searched the OmniXml site but the samples there are as good as non-existing.
Thanks in advance.
回答1:
Some common taks with OmniXML:
Loading the document from file or from stream or string
xml := CreateXMLDoc
xml.Load(FileName);
xml.LoadFromStream(XMLAsStream);
xml.LoadXML(XMLAsString)
Selecting a single node (5th child):
MyNode := XML.ChildNodes.Item[4];
MyNode := XML.SelectSingleNode('Node[5]');
Selecting with XPath
MyNode := XML.SelectSingleNode('/MyNodes/SpecificNodes/Node[5]');
Selecting collection of nodes
MyNodes := XML.SelectNodes('/MyNodes/SpecificNodes/Node');
If you downloaded from http://www.omnixml.com/download.html then there is a directory called demo inside, that contains all the demos. They will explain almost everything to you.
If you decide to use SimpleStorage on top of OmniXML, let me show you how your upper example would look, using SimpleStorage.
xml := StorageFromFile(rssFileName)
for channel in xml.Elements('channel') do
begin
ListBox1.Items.Add('['+channel.Get('title')AsStringDef+']')
for Item in channel.Elements('item') do
ListBox1.Items.Add(' <'+ Item .Get('title')AsStringDef+'>')
end; //for iChannel
No do you see how much boilerplate code was gone (21 lines of code shrunk to 7 for the same functionality). There is no need to check if the node exists etc.. and enumerators help greatly. I strongly suggest you use this approach because it is so much clearer.
回答2:
From the sample link Keeper answered. It was the SelectNodes('..') and SelectSingleNode('...') part I was looking for:
xml := CreateXMLDoc;
if not xml.Load(rssFileName) then
ListBox1.Items.Add('Not an XML document: '+rssFileName)
else begin
channels := xml.DocumentElement.SelectNodes('channel');
for iChannel := 0 to channels.Length-1 do begin
channel := channels.Item[iChannel];
title := channel.SelectSingleNode('title');
if assigned(title) then
ListBox1.Items.Add('['+title.Text+']')
else
ListBox1.Items.Add('[]');
items := channel.SelectNodes('item');
for iItem := 0 to items.Length-1 do begin
title := items.Item[iItem].SelectSingleNode('title');
if assigned(title) then
ListBox1.Items.Add(' <'+title.Text+'>')
else
ListBox1.Items.Add(' <>');
end; //for iItem
end; //for iChannel
end;
It was Sunday and I wanted to ask for a solution before delving into the Omni source code too much :)
I think the author of OmniXml should post such things as sample code on his side.
Thanks.
来源:https://stackoverflow.com/questions/3594015/anyone-has-sample-code-to-load-an-xml-using-omnixml