2013-06-25 2 views
1

제가 작업하고있는 프로젝트가 있는데 Rails 나 Ruby에 대해 많이 알지 못합니다.로컬 XML 파일을 생성하는 데 사용할 수있는 것은 무엇입니까?

사용자 입력에서 XML 파일을 생성해야합니다. 일부 리소스를 사용하면 매우 빠르고 쉽게이 작업을 수행 할 수 있습니다.

+0

정도가 아니다 여기에 가려면 일반성에서 추천해야합니다. 참조 : http://stackoverflow.com/questions/2309011/how-do-i-render-a-builder-template-in-ruby-on-rails –

답변

10

gem에는 XML을 처음부터 만드는 멋진 인터페이스가 있습니다. 여전히 사용하기 쉽지만 강력합니다.

require 'nokogiri' 
builder = Nokogiri::XML::Builder.new do |xml| 
    xml.root { 
    xml.products { 
     xml.widget { 
     xml.id_ "10" 
     xml.name "Awesome widget" 
     } 
    } 
    } 
end 
puts builder.to_xml 

윌 출력 :

<?xml version="1.0"?> 
<root> 
    <products> 
    <widget> 
     <id>10</id> 
     <name>Awesome widget</name> 
    </widget> 
    </products> 
</root> 

또한, Ox도이 작업을 수행 그것은 내 취향이다. 여기에 documenation의 샘플입니다 :

require 'ox' 

doc = Ox::Document.new(:version => '1.0') 

top = Ox::Element.new('top') 
top[:name] = 'sample' 
doc << top 

mid = Ox::Element.new('middle') 
mid[:name] = 'second' 
top << mid 

bot = Ox::Element.new('bottom') 
bot[:name] = 'third' 
mid << bot 

xml = Ox.dump(doc) 

# xml = 
# <top name="sample"> 
# <middle name="second"> 
#  <bottom name="third"/> 
# </middle> 
# </top> 
+0

감사합니다! 나는 이것을 시도 할 것이다! – ironmantis7x

0

노코 기리가 libxml2를 주위에 래퍼입니다.

Gemfile 보석 '노코 기리' 이 결과는 같은 모양이

xml = Nokogiri::XML::Builder.new { |xml| 
    xml.body do 
     xml.node1 "some string" 
     xml.node2 123 
     xml.node3 do 
      xml.node3_1 "another string" 
     end 
     xml.node4 "with attributes", :attribute => "some attribute" 
     xml.selfclosing 
    end 
}.to_xml 

처럼 노코 기리 XML 빌더 XML 간단한 사용을 생성하려면

<?xml version="1.0"?> 
<body> 
    <node1>some string</node1> 
    <node2>123</node2> 
    <node3> 
    <node3_1>another string</node3_1> 
    </node3> 
    <node4 attribute="some attribute">with attributes</node4> 
    <selfclosing/> 
</body> 

출처 : http://www.jakobbeyer.de/xml-with-nokogiri

관련 문제