如何保存未转义&在nokogiri xml? [英] How to save unescaped & in nokogiri xml?
问题描述
如何使用nokogiri在最终xml文件中保存&
How can I save &
in the final xml file using nokogiri?
我的代码如下:
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) }
,输出类似于
<?xml version="1.0"?>
<project>
<arg line="how to save only &???"/>
</project>
更新
看起来我可以使用CDATA但不知道如何使用它与nokogiri。我使用 @doc = Nokogiri :: XML(File.open(file_name))
推荐答案
您不能将XML中的未转义的&
放在XML中。以下是 W3规范XML :
You can't put an unescaped &
in XML as you wish. Here is from the W3 spec for XML:
与字符(&)和左角括号(<)不得以其文字形式出现,除非用作标记分隔符,或在注释中,处理指令或CDATA部分。如果需要其他地方,则必须使用数字字符引用或字符串&和<分别转义。
The ampersand character (&) and the left angle bracket (<) MUST NOT appear in their literal form, except when used as markup delimiters, or within a comment, a processing instruction, or a CDATA section. If they are needed elsewhere, they MUST be escaped using either numeric character references or the strings " & " and " < " respectively.
<关于在Nokogiri中使用CDATA,这里是info , Nokogiri的网站,如果您使用Nokogiri :: XML :: Builder来构建您的XML。
As for using CDATA in Nokogiri, here is info from Nokogiri's site, if you use Nokogiri::XML::Builder to build your XML.
更新:这是我在注释中提到的示例中的代码。
UPDATE: Here is the code from my example mentioned in comments.
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
---我正在使用的一个例子。 ---
--- And an example of what I was working with. ---
<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>
这篇关于如何保存未转义&在nokogiri xml?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!