如何保存unescaped和nokogiri xml?

如何使用nokogiri保存&在最终的xml文件中?

我的代码是这样的:

 require 'rubygems' require 'nokogiri' file_name = "amp.xml" @doc = Nokogiri::XML('') 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) } 

而输出就像

     

UPDATE

看起来我可以使用CDATA,但不知道如何使用它与nokogiri。 我使用@doc = Nokogiri::XML(File.open(file_name))读取xml文件

您不能按照自己的意愿将未转义的XML格式化。 这是来自W3规范的XML :

&符号(&)和左尖括号(<)绝不能以字面形式出现,除非用作标记分隔符,或用于注释,处理指令或CDATA部分。 如果在其他地方需要它们,它们必须分别使用数字字符引用或字符串“&”和“<”进行转义。

至于在Nokogiri中使用CDATA,如果您使用Nokogiri :: XML :: Builder来构建XML, 这里是来自Nokogiri网站的信息 。

更新:这是我在评论中提到的示例中的代码。

 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_ tq t.answers.each { |c| xml.a(point: cp) { xml.text ca } } } 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 

---和我一起工作的一个例子。 ---

   How do you feel about sports? I don't have any interest in sports. I like to play sports. I follow college or professional sports.