草庐IT

xml - Delphi XML 遍历

coder 2024-06-27 原文

我是 Delphi 的新手。

我想找到每个主题下的所有作者。

这是我的 XML

<?xml version="1.0"?>
<catalog>
   <subject id="computer">
       <book id="bk101">                                                            
          <author>Gambardella, Matthew</author>                                  
          <title>XML Developer's Guide</title>                                   
          <genre>Computer</genre>                                                
          <price>44.95</price>                                                   
          <publish_date>2000-10-01</publish_date>                                
          <description>An in-depth look at creating applications                 
          with XML.</description>                                                
       </book>                                                                   
       <book id="bk112">                                                         
          <author>Galos, Mike</author>                                           
          <title>Visual Studio 7: A Comprehensive Guide</title>                  
          <genre>Computer</genre>                                                
          <price>49.95</price>                                                   
          <publish_date>2001-04-16</publish_date>                                
          <description>Microsoft Visual Studio 7 is explored in depth,           
          looking at how Visual Basic, Visual C++, C#, and ASP+ are              
          integrated into a comprehensive development                            
          environment.</description>                                             
       </book>                                                                   
   </subject>
   <subject id="literature">
       <book id="bk102">                                                         
          <author>Ralls, Kim</author>                                            
          <title>Midnight Rain</title>                                           
          <genre>Fantasy</genre>                                                 
          <price>5.95</price>                                                    
          <publish_date>2000-12-16</publish_date>                                
          <description>A former architect battles corporate zombies,             
          an evil sorceress, and her own childhood to become queen               
          of the world.</description>                                            
       </book>                                                                   
       <book id="bk103">                                                         
          <author>Corets, Eva</author>                                           
          <title>Maeve Ascendant</title>                                         
          <genre>Fantasy</genre>                                                 
          <price>5.95</price>                                                    
          <publish_date>2000-11-17</publish_date>                                
          <description>After the collapse of a nanotechnology                    
          society in England, the young survivors lay the                        
          foundation for a new society.</description>                            
       </book>                                                                   
       <book id="bk104">                                                         
          <author>Corets, Eva</author>                                           
          <title>Oberon's Legacy</title>                                         
          <genre>Fantasy</genre>                                                 
          <price>5.95</price>                                                    
          <publish_date>2001-03-10</publish_date>                                
          <description>In post-apocalypse England, the mysterious                
          agent known only as Oberon helps to create a new life                  
          for the inhabitants of London. Sequel to Maeve                         
          Ascendant.</description>                                               
       </book>                                                                   
       <book id="bk105">                                                         
          <author>Corets, Eva</author>                                           
          <title>The Sundered Grail</title>                                      
          <genre>Fantasy</genre>                                                 
          <price>5.95</price>                                                    
          <publish_date>2001-09-10</publish_date>                                
          <description>The two daughters of Maeve, half-sisters,                 
          battle one another for control of England. Sequel to                   
          Oberon's Legacy.</description>                                         
       </book>                                                                   
       <book id="bk106">                                                         
          <author>Randall, Cynthia</author>                                      
          <title>Lover Birds</title>                                             
          <genre>Romance</genre>                                                 
          <price>4.95</price>                                                    
          <publish_date>2000-09-02</publish_date>                                
          <description>When Carla meets Paul at an ornithology                   
          conference, tempers fly as feathers get ruffled.</description>         
       </book>                                                                   
       <book id="bk107">                                                         
          <author>Thurman, Paula</author>                                        
          <title>Splish Splash</title>                                           
          <genre>Romance</genre>                                                 
          <price>4.95</price>                                                    
          <publish_date>2000-11-02</publish_date>                                
          <description>A deep sea diver finds true love twenty                   
          thousand leagues beneath the sea.</description>                        
       </book>                                                                   
       <book id="bk108">                                                         
          <author>Knorr, Stefan</author>                                         
          <title>Creepy Crawlies</title>                                         
          <genre>Horror</genre>                                                  
          <price>4.95</price>                                                    
          <publish_date>2000-12-06</publish_date>                                
          <description>An anthology of horror stories about roaches,             
          centipedes, scorpions  and other insects.</description>                
       </book>                                                                   
       <book id="bk109">                                                         
          <author>Kress, Peter</author>                                          
          <title>Paradox Lost</title>                                            
          <genre>Science Fiction</genre>                                         
          <price>6.95</price>                                                    
          <publish_date>2000-11-02</publish_date>                                
          <description>After an inadvertant trip through a Heisenberg            
          Uncertainty Device, James Salway discovers the problems                
          of being quantum.</description>                                        
       </book>                                                                   
       <book id="bk110">                                                         
          <author>O'Brien, Tim</author>                                          
          <title>Microsoft .NET: The Programming Bible</title>                   
          <genre>Computer</genre>                                                
          <price>36.95</price>                                                   
          <publish_date>2000-12-09</publish_date>                                
          <description>Microsoft's .NET initiative is explored in                
          detail in this deep programmer's reference.</description>              
       </book>                                                                   
       <book id="bk111">                                                         
          <author>O'Brien, Tim</author>                                          
          <title>MSXML3: A Comprehensive Guide</title>                           
          <genre>Computer</genre>                                                
          <price>36.95</price>                                                   
          <publish_date>2000-12-01</publish_date>                                
          <description>The Microsoft MSXML3 parser is covered in                 
          detail, with attention to XML DOM interfaces, XSLT processing,         
          SAX and more.</description>                                            
       </book>                                                                   
   </subject>
</catalog>

最佳答案

您可以使用 XPath选择所有作者,使用像这样的表达式>easy 是使用 Microsoft XML DOM implementation

检查这个示例应用程序

{$APPTYPE CONSOLE}

uses
  ActiveX,
  Variants,
  ComObj,
  SysUtils;

procedure ReadXMLFile(const FileName:TFileName);
const
  Msxml2_DOMDocument='Msxml2.DOMDocument.6.0';
var
  XmlDoc         : OleVariant;
  Nodes          : OleVariant;
  lNodes         : Integer;
  i              : Integer;
begin
  //create an instance to the XML DOM 
  XmlDoc       := CreateOleObject(Msxml2_DOMDocument);
  try
    XmlDoc.Async := False;
    //load the file
    XmlDoc.Load(FileName);
    //set the xpath mode
    XmlDoc.SetProperty('SelectionLanguage','XPath');
    //check for errors in the xml file
      if (XmlDoc.parseError.errorCode <> 0) then
       raise Exception.CreateFmt('Error in Xml Data %s',[XmlDoc.parseError]);

    //select the nodes with match with the expression
    Nodes := XmlDoc.selectNodes('//catalog/subject/book/author');
    //get the number of nodes selected
    lNodes:= Nodes.Length;
    Writeln(Format('%d Authors found',[lNodes]));
    //traverse the nodes
     for i:=0 to Nodes.Length - 1 do
      Writeln(Format('Author Name %s',[Nodes.Item(i).Text]));

  finally
   XmlDoc :=Unassigned;
  end;
end;


begin
 try
    CoInitialize(nil);
    try
      ReadXMLFile(ExtractFilePath(ParamStr(0))+'test.xml');
    finally
      CoUninitialize;
    end;
 except
    on E:Exception do
        Writeln(E.Classname, ':', E.Message);
 end;
 Writeln('Press Enter to exit');
 Readln;      
end.

最后应用会返回这个

12 Authors found
Author Name Gambardella, Matthew
Author Name Galos, Mike
Author Name Ralls, Kim
Author Name Corets, Eva
Author Name Corets, Eva
Author Name Corets, Eva
Author Name Randall, Cynthia
Author Name Thurman, Paula
Author Name Knorr, Stefan
Author Name Kress, Peter
Author Name O'Brien, Tim
Author Name O'Brien, Tim

关于xml - Delphi XML 遍历,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5968467/

有关xml - Delphi XML 遍历的更多相关文章

  1. ruby-on-rails - 在 Ruby 中循环遍历多个数组 - 2

    我有多个ActiveRecord子类Item的实例数组,我需要根据最早的事件循环打印。在这种情况下,我需要打印付款和维护日期,如下所示:ItemAmaintenancerequiredin5daysItemBpaymentrequiredin6daysItemApaymentrequiredin7daysItemBmaintenancerequiredin8days我目前有两个查询,用于查找maintenance和payment项目(非排他性查询),并输出如下内容:paymentrequiredin...maintenancerequiredin...有什么方法可以改善上述(丑陋的)代

  2. ruby-on-rails - 如何从 format.xml 中删除 <hash></hash> - 2

    我有一个对象has_many应呈现为xml的子对象。这不是问题。我的问题是我创建了一个Hash包含此数据,就像解析器需要它一样。但是rails自动将整个文件包含在.........我需要摆脱type="array"和我该如何处理?我没有在文档中找到任何内容。 最佳答案 我遇到了同样的问题;这是我的XML:我在用这个:entries.to_xml将散列数据转换为XML,但这会将条目的数据包装到中所以我修改了:entries.to_xml(root:"Contacts")但这仍然将转换后的XML包装在“联系人”中,将我的XML代码修改为

  3. 【Java入门】使用Java实现文件夹的遍历 - 2

    遍历文件夹我们通常是使用递归进行操作,这种方式比较简单,也比较容易理解。本文为大家介绍另一种不使用递归的方式,由于没有使用递归,只用到了循环和集合,所以效率更高一些!一、使用递归遍历文件夹整体思路1、使用File封装初始目录,2、打印这个目录3、获取这个目录下所有的子文件和子目录的数组。4、遍历这个数组,取出每个File对象4-1、如果File是否是一个文件,打印4-2、否则就是一个目录,递归调用代码实现publicclassSearchFile{publicstaticvoidmain(String[]args){//初始目录Filedir=newFile("d:/Dev");Datebeg

  4. ruby - Chef Ruby 遍历 .erb 模板文件中的属性 - 2

    所以这可能有点令人困惑,但请耐心等待。简而言之,我想遍历具有特定键值的所有属性,然后如果值不为空,则将它们插入到模板中。这是我的代码:属性:#===DefaultfileConfigurations#default['elasticsearch']['default']['ES_USER']=''default['elasticsearch']['default']['ES_GROUP']=''default['elasticsearch']['default']['ES_HEAP_SIZE']=''default['elasticsearch']['default']['MAX_OP

  5. ruby - 如何遍历 Ruby 中所有正则表达式匹配的字符串? - 2

    我们有一个字符串:“”这个正则表达式://i如何从当前字符串中获取所有匹配项? 最佳答案 "".scan(//)参见scan在ruby​​-docs上 关于ruby-如何遍历Ruby中所有正则表达式匹配的字符串?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/6857852/

  6. ruby-on-rails - 如何在 Rails 3 中禁用 XML 解析 - 2

    我想禁用HTTP参数的自动XML解析。但我发现命令仅适用于Rails2.x,它们都不适用于3.0:config.action_controller.param_parsers.deleteMime::XML(application.rb)ActionController::Base.param_parsers.deleteMime::XMLRails3.0中的等价物是什么? 最佳答案 根据CVE-2013-0156的最新安全公告你可以将它用于Rails3.0。3.1和3.2ActionDispatch::ParamsParser::

  7. ruby - 如何使用 Nokogiri::XML::Builder 生成动态标签? - 2

    我正在遍历数组中的一组标签名称,我想使用构建器打印每个标签名称,而不是求助于“我认为:builder=Nokogiri::XML::Builder.newdo|xml|fortagintagsxml.tag!tag,somevalendend会这样做,但它只是创建名称为“tag”的标签,并将标签变量作为元素的文本值。有人可以帮忙吗?这个看起来应该比较简单,我刚刚在搜索引擎上找不到答案。我可能没有以正确的方式提问。 最佳答案 尝试以下操作。如果我没记错的话,我添加了一个根节点,因为Nokogiri需要一个。builder=Nokogi

  8. ruby - 如何让 Nokogiri 解析并返回 XML 文档? - 2

    这是一些奇怪的例子:#!/usr/bin/rubyrequire'rubygems'require'open-uri'require'nokogiri'print"withoutread:",Nokogiri(open('http://weblog.rubyonrails.org/')).class,"\n"print"withread:",Nokogiri(open('http://weblog.rubyonrails.org/').read).class,"\n"运行此返回:withoutread:Nokogiri::XML::Documentwithread:Nokogiri::

  9. ruby - 循环遍历数组的元素 - 2

    我想从0到2循环@a:0,1,2,0,1,2。defset_aif@a==2@a=0else@a=@a+1endend也许有更好的方法? 最佳答案 (0..2).cycle(3){|x|putsx}#=>0,1,2,0,1,2,0,1,2item=[0,1,2].cycle.eachitem.next#=>0item.next#=>1item.next#=>2item.next#=>0... 关于ruby-循环遍历数组的元素,我们在StackOverflow上找到一个类似的问题:

  10. ruby-on-rails - 如何在 Rails View 中遍历数组? - 2

    我在MySql中进行了查询,但在Rails和mysql2gem中工作。信息如下:http://sqlfiddle.com/#!2/9adb8/6查询工作正常,没有问题,并显示以下结果:UNITV1A1N1V2A2N2V3A3N3V4A4N4V5A5N5LIFE200120000000000ROB010012000000000-为rails2.3.8安装了mysql2gemgeminstallmysql2-v0.2.6-创建Controller:classPolicyController这是日志:SQL(0.9ms)selectdistinct@sql:=concat('SELECTpb

随机推荐