如何使用Ruby计算XML字符串中的特定节点



我有一个这样的字符串:

text = <<-XML
<?xml version="1.0" encoding="UTF-8" ?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>https://www.my9.jp/LanLT/index.cfm?fuseaction=job.detail&amp;sgtno=Job-000002</loc>
<lastmod>2019-10-04</lastmod>
<changefreq>daily</changefreq>
<priority>0.8</priority>
</url>
<url>
<loc>https://www.my9.jp/LanLT/index.cfm?fuseaction=job.detail&amp;sgtno=samnangtest002</loc>
<lastmod>2019-10-01</lastmod>
<changefreq>daily</changefreq>
<priority>0.8</priority>
</url>
<url>
<loc>https://www.my9.jp/LanLT/index.cfm?fuseaction=job.detail&amp;sgtno=Job-000006</loc>
<lastmod>2019-10-04</lastmod>
<changefreq>daily</changefreq>
<priority>0.8</priority>
</url>
</urlset>
XML

我想计算以<url>开头、以</url>结尾的子字符串的数量。例如,在这个字符串中,结果是3。

为作业使用正确的工具。用于解析HTML或XML数据的工具-Nokogiri

require 'nokogiri'
count = Nokogiri::XML.parse(text).root.children.count {|node| node.name == "url" }

如果您也想(递归地(从孙计算所有<url>节点,那么尝试traverse方法(regex方法在这种情况下不起作用(

count = 0
Nokogiri::XML.parse(text).traverse { |node| count += 1 if node.name == "url" }
puts count # => 3

您不应该使用regex来解析xml数据。Regex不是为这个而设计的,而且很容易出错。

text.scan(/<url>.*?</url>/m).size

m代表多行。

正则表达式模式搜索由<url></url>封装的内容。

最新更新