2011-08-02 14 views
0

nokogiriを使用して&を最終的なxmlファイルに保存するにはどうすればよいですか?エスケープされていない&nokogiri xmlを保存するには?

require 'rubygems' 
require 'nokogiri' 

    file_name = "amp.xml" 
    @doc = Nokogiri::XML('<project/>') 

    arg = Nokogiri::XML::Node.new "arg", @doc 
    arg['line'] = "how to save only &???" 
    @doc.root.add_child(arg) 

    File.open(file_name, 'w') {|f| f.write(@doc.to_xml) } 

、出力は私が鋸山でそれを使用する方法がわからCDATAを使用することはできませんが、同じようUPDATE

が見える

<?xml version="1.0"?> 
<project> 
    <arg line="how to save only &amp;???"/> 
</project> 

のようなものです:

私のコードは次のようです。 @doc = Nokogiri::XML(File.open(file_name))

+3

'&'は不正なxml文字ですが、エスケープして保存することはできません。この質問は違法な文字についてです。http://stackoverflow.com/questions/730133/invalid-characters-in-xml –

答えて

3

エスケープされていない&をXML形式で入力することはできません。ここでW3 spec for XMLからです:

アンパサンド文字(&)とそのリテラル形式で現れてはならない左アングルブラケット(<)、マークアップ区切り文字として使用する、またはコメント内の場合を除いて、処理命令、またはCDATAセクション。他の場所で必要な場合は、数値文字参照か "&"と "<"という文字列を使用してエスケープする必要があります。あなたはXMLを構築するために鋸山:: XML :: Builderを使用している場合、鋸山のサイトから鋸山、here is infoにCDATAを使用するよう

更新:コメントに記載されている私の例のコードです。

module Questions 
    @source = File.dirname(__FILE__) + '/questions.xml' 
    def parse 
    if File.exists?(@source) 
     File.open(@source, 'r+') do |document| 
     q = {} 
     text = Nokogiri::XML::Document.parse(document) 
     text.xpath('.//question').each do |c| 
      parent = c.attribute_nodes[2].to_s 
      q[:type] = c.attribute_nodes[1].to_s.to_sym # => question type 
      q[:q_id] = c.attribute_nodes[0].to_s # => question type 
      q[:question] = c.xpath('.//q').first.content # => question 
      q[:answers] = [] 
      c.xpath('.//a').each { |ans| 
      p = ans.attribute_nodes.first.value # => point value 
      a = ans.content # => answer 
      q[:answers] << [a, p] 
      } 
      if parent == "NA" 
      Question.create!(q) 
      else 
      Question.first(conditions: {q_id: parent}).children << Question.create!(q) 
      end 
     end 
     end 
    end 
    end 

    def write 
    builder = Nokogiri::XML::Builder.new do |xml| 
     xml.root { 
     Question.each do |t| 
      xml.question(id: t.id, type: t.type, parent: t.parent) { 
      xml.q_ t.q 
      t.answers.each { |c| 
       xml.a(point: c.p) { xml.text c.a } 
      } 
      } 
     end 
     } 
    end 
    document = builder.to_xml 
    File.open(@source, 'w+') do |f| 
     f.puts document 
    end 
    end # end write 

    module_function :parse 
    module_function :write 
end 

---私がどのように作業していたかの例。 ---

<question id="q0000" type="root" parent="NA"> 
    <q>How do you feel about sports?</q> 
    <a point="0">I don't have any interest in sports.</a> 
    <a point="q0001">I like to play sports.</a> 
    <a point="q0002">I follow college or professional sports.</a> 
    </question> 
+0

私はビルダーを使用しません。または、私は私の '更新'のようにxmlファイルを読み込んだ場合、ビルダーの使い方を知らない。 – Radek

+0

NokogiriでXMLを行った唯一の方法はBuilderです。他の誰かがあなたの方法を助けてくれることを願っています。 –

+0

ビルダーを使用してxmlファイルを読み取ることはできますか? – Radek

関連する問題