使用 Nokogiri 根据用户在 Rails 应用程序中的输入搜索 XML 文件 [英] Using Nokogiri to search through XML file based on user input in Rails app

查看:46
本文介绍了使用 Nokogiri 根据用户在 Rails 应用程序中的输入搜索 XML 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个 XML 文件(XML 文件)架构(XML 架构).

So I've got an XML file (XML file) with a schema (XML schema).

我正在尝试创建一个快速的 Rails 应用程序,以允许用户根据作为 sdnEntry 元素的子元素的lastName"元素搜索 XML 文件.

I'm trying to create a quick Rails app to allow users to search through the XML file based on the 'lastName" element that are children of an sdnEntry element.

我在设置 rails 应用程序或搜索表单时没有遇到任何问题.我还能够使用 Nokogiri 加载 XML 文件,并且可以运行简单的命令,例如...

I don't have any problems setting up the rails app, or the search-form. I was also able to get the XML file loaded using Nokogiri and can run simple commands like...

xmldoc.css("lastName")

...返回一个包含所有lastName"元素的节点集.不幸的是,这还不够好,因为它不仅列出了sdnEntry"元素正下方的lastName"元素.另外,这甚至没有让我开始从表单插入用户的输入.我在想这样的事情会起作用...

...to return a NodeSet with all the 'lastName' elements in them. Unfortunately, that's not good enough, since that lists not just the 'lastName' elements directly underneath an 'sdnEntry' element. Plus that doesn't even get me started to insert the user's input from the form. I was thinking something like this would work...

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

...但这没有用.奇怪的是,我什至无法得到...

...but that didn't work. Oddly, I couldn't even get...

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

...开始工作.我只是对 XML 文档的 Nokogiri 或 XPath 或 CSS 查询知之甚少,无法弄清楚如何从用户输入表单传递参数以创建适当的查询,从而为我返回正确的信息.

...to work. I just don't know enough about Nokogiri or XPath or CSS queries for XML documents to figure out how to pass the param from user-input form to create the appropriate query that will return the right info for me.

我尝试浏览 Nokogiri 文档W3Schools XPath 教程.没有快乐.

I tried looking through the Nokogiri Documentation and the W3Schools XPath Tutorial. No joy.

我非常感谢任何指针、代码片段或建议.谢谢.

I would really appreciate any pointers, code snippets or suggestions. Thank you.

推荐答案

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()开始于().

Instead of requiring the exact text value, you might also be interested in the XPath functions contains() or starts-with().

这篇关于使用 Nokogiri 根据用户在 Rails 应用程序中的输入搜索 XML 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆