【发布时间】:2012-03-31 06:07:34
【问题描述】:
我想从一个网站解析几千个 XML 文件(我有权限) 并且必须使用 SAX 来避免将文件加载到内存中。然后将它们保存到 CSV 文件中。
xml 文件如下所示:
<?xml version="1.0" encoding="UTF-8"?><educationInfo xmlns="http://skolverket.se/education/info/1.2" xmlns:ct="http://skolverket.se/education/commontypes/1.2" xmlns:nya="http://vhs.se/NyA-emil-extensions" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" expires="2013-08-01" id="info.uh.su.HIA80D" lastEdited="2011-10-13T10:10:05" xsi:schemaLocation="http://skolverket.se/education/info/1.2 educationinfo.xsd">
<titles>
<title xml:lang="sv">Arkivvetenskap</title>
<title xml:lang="en">Archival science</title>
</titles>
<identifier>HIA80D</identifier>
<educationLevelDetails>
<typeOfLevel>uoh</typeOfLevel>
<typeOfResponsibleBody>statlig</typeOfResponsibleBody>
<academic>
<course>
<type>avancerad</type>
</course>
</academic>
</educationLevelDetails>
<credits>
<exact>60</exact>
</credits>
<degrees>
<degree>Ingen examen</degree>
</degrees>
<prerequisites>
<academic>uh</academic>
</prerequisites>
<subjects>
<subject>
<code source="vhs">10.300</code>
</subject>
</subjects>
<descriptions>
<ct:description xml:lang="sv">
<ct:text>Arkivvetenskap rör villkoren för befintliga arkiv och modern arkivbildning med fokus på arkivarieyrkets arbetsuppgifter: bevara, tillgängliggöra och styra information. Under ett år behandlas bl a informations- och dokumenthantering, arkivredovisning, gallring, lagstiftning och arkivteori. I kursen ingår praktik, där man under handledning får arbeta med olika arkivarieuppgifter.</ct:text>
</ct:description>
</descriptions>
</educationInfo>
我使用此代码模板,请检查我的 cmets 是否有问题:
class InfoData < Nokogiri::XML::SAX::Document
def initialize
# do one-time setup here, called as part of Class.new
# But what should I use hashes or arrays?
end
def start_element(name, attributes = [])
# check the element name here and create an active record object if appropriate
# How do I grab specific element like: ct:text ?
# how do I grab root-element?
end
def characters(s)
# save the characters that appear here and possibly use them in the current tag object
end
def end_element(name)
# check the tag name and possibly use the characters you've collected
# and save your activerecord object now
end
end
parser = Nokogiri::XML::SAX::Parser.new(InfoData.new)
# How do I parse every xml-link?
parser.parse_file('')
我写了这个方法来获取链接,但不知道在类中的什么地方使用它或者我是否应该在那里使用它:
@items = Set.new
def get_links(url)
doc = Nokogiri::HTML(open(url))
doc.xpath('//a/@href').each do |url|
item = {}
item[:url] = url.content
items << item
end
【问题讨论】:
-
如果那个 XML 样本是一个完整的 XML 文件,我会使用 DOM,而不是 SAX,因为它更容易一些。如今,大多数主机都有数 GB 的 RAM,这使得 SAX 变得不那么重要了。 SAX 将更快地处理 BIG XML 文件,但您的开发时间可能会更长。
-
@theTinMan 我尝试使用 DOM 解析它,但它不起作用。它大约有 46000 个 xml 文件。它使用 SAX 解析的正确方法..
标签: ruby nokogiri sax web-crawler