2011-11-05 33 views
1

所以我有一个XML文件(XML file)和一个模式(XML schema)。使用Nokogiri在Rails应用中根据用户输入搜索XML文件

我试图创建一个快速Rails应用程序,允许用户通过基于XML文件的“姓氏”元素是一个sdnEntry元素的儿童中进行检索,

我没有任何问题,设置铁路钢轨的应用程序,或搜索形式,我也能得到利用引入nokogiri,可以运行像简单的命令加载XML文件...

xmldoc.css("lastName") 

...与返回一个节点集所有的' lastName'元素,不幸的是,这不够好,因为它不仅列出了直接在'sdnEntry'元素下面的'lastName'元素,甚至不会让我开始从表单插入用户的输入。我正在想这样的事情会工作...

xmldoc.xpath("/xmlns:sdnList/sdnEntry/lastName[text()='#{param[:name]}']") 

...但没有奏效。奇怪的是,我什至不能得到...

xmldoc.xpath("/xmlns:sdnList/sdnEntry/lastName") 

...工作。对于XML文档的Nokogiri或XPath或CSS查询,我只是不够了解如何从用户输入表单传递参数来创建适当的查询,以便为我返回正确的信息。

我试着翻翻Nokogiri DocumentationW3Schools XPath Tutorial。没有快乐。

我真的很感谢任何指针,代码片段或建议。谢谢。

+0

有关名称空间和nokogiri的更多信息,请参阅http://stackoverflow.com/questions/4690737/nokogiri-xpath-namespace-query/4691008#4691008 –

回答

1
user_input = "CHOMBO"    # However you are getting it 
doc = Nokogiri.XML(myxml,&:noblanks) # However you are getting it 
doc.remove_namespaces!    # Simplify your life, if you're just reading 

# Find all sdnEntry elements with a lastName element with specific value 
sdnEntries = doc.xpath("/sdnList/sdnEntry[lastName[text()='#{user_input}']]") 

sdnEntries.each do |sdnEntry| 
    p [ 
    sdnEntry.at_xpath('uid/text()').content, # You can get a text node's contents 
    sdnEntry.at_xpath('firstName').text  # …or get an element's text 
    ] 
end 
#=> ["7491", "Ignatius Morgan"] 
#=> ["9433", "Marian"] 
#=> ["9502", "Ever"] 

,而不是要求的确切文字的价值,你可能也有兴趣在XPath功能contains()starts-with()

2

您的问题与Nokogiri正在使用的XPath相同。您需要指定名称空间在属性中的含义。更多信息,请致电Nokogiri documentation

以下是查找项目的示例,使用您的参数可能也适用。

doc = Nokogiri::XML(File.read("sdn.xml")) 
doc.xpath("//sd:lastName[text()='INVERSIONES EL PROGRESO S.A.']", "sd"=>"http://tempuri.org/sdnList.xsd") 

>> [#<Nokogiri::XML::Element:0x80b35350 name="lastName" namespace=#<Nokogiri::XML::Namespace:0x80b44c4c href="http://tempuri.org/sdnList.xsd"> children=[#<Nokogiri::XML::Text:0x80b34e3c "INVERSIONES EL PROGRESO S.A.">]>] 
+0

感谢您的回复Rob。上面的答案提前了一点,还包括了一些我可能感兴趣的XPath函数的相关信息。也就是说,你的工作也是如此。谢谢 – GreenPlastik

相关问题