I'm new to learning Rails and currently trying to complete a project for school that involves using of XML along with an MVC architecture. I'm using Rails as my MVC and I just want to know how I should approach adding in the XML and then rendering it to display that information.
I know that xml.builder allows me to build the XML using more DRY philosophy but I'm looking for a good tutorial that would explain the process of doing that and then display it in my browser. Any information is appreciated. Thanks in advance.
You can use from_xml to parse XML data to hash:
xml = <<-XML
<?xml version="1.0" encoding="UTF-8"?>
<hash>
<foo type="integer">1</foo>
<bar type="integer">2</bar>
</hash>
XML
hash = Hash.from_xml(xml)
# => {"hash"=>{"foo"=>1, "bar"=>2}}
Reading from a local file:
# reading the file content into a variable
xml_file = File.read("my_xml_file.xml")
hash = Hash.from_xml(xml_file)
Reference:
https://apidock.com/rails/v4.2.7/Hash/from_xml/class
Related
I'm trying to convert an XML document into a Ruby hash for the first time, and having no success. I have my XML document, doc.xml, in a folder along with my script hashrunner.rb.
In hashrunner.rb:
require 'active_support/core_ext/hash'
hash = Hash.from_xml("doc.xml")
puts hash
The first line of the XML document is <?xml version="1.0" encoding="US-ASCII"?>, if that is helpful.
In my console, when I run ruby hashrunner.rb, I get the error message:
/Users/me/.rvm/gems/ruby-1.9.3-p374/gems/activesupport-4.0.0/lib/active_support/xml_mini/rexml.rb:34:in `parse':The document "doc.xml" does not have a valid root (REXML::ParseException)
As someone relatively new to Ruby, I don't understand what this means, and some internet searching didn't turn up an explanation, either. To start, I'm not even sure if I'm calling the XML file correctly in the from_xml method, so please let me know if that's the case. I'd be open to using different gems or a different approach if that would help.
I'm pretty sure Hash::from_xml has to take an XML string, not a filename string. Try:
hash = Hash.from_xml(File.read("doc.xml"))
I've search the web for a solution. I am developing an application that fetches some xml content from a webserver. I can run the xml code in a log and every thing is returned OK. So that is working.
My problem is when it is time to parse the xml. My xml code looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<Content>
<Name>
John Doe
</Name>
<Adress>
Road 123
</Adress>
</Content>
How can grab the Name and the adress element and put the string "John Doe" and "Road 123" inside a string.
I hope someone can help me because i am really confused :s
Duplicate of many many many questions...
Try googling "XML Parsing iOS" - in fact please try googling your problem before posting any question on Stack Overflow.
Anyway, I'll give you a clue - have a look at NSXMLParser
I have a string that is a bunch of XML tags.
Basically there is the contents to one tag I want and ignore everything else:
The input would look like:
<Some><XML><stuff>
<title type='text'>key</title>
<Some><other><XML><stuff>
The output would look like:
key
I'm not sure if XML is appropriate since there doesn't seem very much structure to this particular XML.
Can regex do this in RoR or is it more of just a pattern matching thing (true or false) in ruby on rails?
Thanks so much!
Cheers,
Zigu
No. If your source could not be strictly valid XML, I strongly suggest you to use Nokogiri.
Handle the source as an HTML document and extract the info you need in this way:
doc = Nokogiri::HTML("Your string with <key>some value</key>"))
doc.search('key').each do |value|
puts value.content # do whatever you want
end
Here's why you don't parse xml with regexen: RegEx match open tags except XHTML self-contained tags
I'm trying to render a large (ish) array of objects as a plist in Ruby on Rails. The collection currently contains up to 200 objects, each of which is essentially a record (dictionary of keys/values). The overall result format is a plist (as used by Apple) but logically it is not much different from any XML document.
The problem I've hit is rendering the array takes about a second with 200 objects, which seems incredibly slow to me. I'm currently using code like this:
def plistify(collection)
resultarray=Array.new()
collection.each do |entry|
hash= entry.attributes
hash["credits"]= entry.credits
hash["ratingcount"]= entry.ratings.count
hash["entryrating"]= entry.detail_rating
hash["entryratingcount"]= entry.entryratingcount
resultarray << hash
end
{'entries'=>resultarray}.to_plist
end
Which is then sent to the client using:
format.text {render :text => plistify(#entries)}
The resulting output looks something like:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>entries</key>
<array> <-- corresponds to resultarray above
<dict> <-- corresponds to a single entry's attributes above. one of these per entry.
<key>cached_review_id</key>
<integer>190</integer>
<key>cached_tag_list</key>
<string>pub restaurant food waitress</string>
<key>created_at</key>
<date>2009-05-31T13:47:10Z</date>
...about 20 key/values...
etc. Almost all the overhead is in the ruby 'plistify' code - the database overhead is minimal by comparison.
Assuming the overhead might be from creating lots of temporary ruby objects, I've tried replacing all this with a view, and using a Builder in the view to create the same XML document - it works but is actually twice as slow!
Any ideas for how to improve on this, or otherwise identify the bottleneck?
Not sure if there is much you can do to improve this without hacking about in the plist gem itself. Taking a look at the source code from the repository here "svn checkout http://plist.rubyforge.org/svn/" and here it looks like the gem is generating the XML all on its own as opposed to using an XML library (like LibXML, Nokogiri or builder).
I am not sure how much of a difference using one of these libraries will make in generating the XML (they are definitely faster at parsing) for you but it seems to be the first logical place to look for optimization opportunities.
Two questions:
How can I import a file from a web address, without a form?
Example: Organisation.import(:from => 'http://wufoo.com/report.csv')
How can I use xml builder without pulling from the db?
More Info
My company uses wufoo for web forms. The data from wufoo is exported as csv files. To get the data into my company's cms, it needs to be formatted as xml. I don't need to store any of the data, aside from the url to the csv file. I thought this might work well as a simple rails app.
Use open-uri (http://www.ruby-doc.org/stdlib/libdoc/open-uri/rdoc/) to fetch the file, and ruby's csv library to parse it. Or, use csv-mapper which is nice and simple (http://csv-mapper.rubyforge.org/).
Here is a way:
require 'rio'
require 'fastercsv'
url = 'http://remote-url.com/file.csv'
people = FasterCSV.parse(rio(url).read)
xml = ''
1.upto(people.size-1) do |row_idx|
xml << " <record>\n"
people[0].each_with_index do |column, col_idx|
xml << " <#{column.parameterize}>#{people[row_idx][col_idx]}</#{column.parameterize}>\n"
end
xml << " </record>\n"
end