如何在 Nokogiri 中创建 <text>...</text> 节点?
How to create <text>...</text> node in Nokogiri?
我需要这样xml:
<jobs>
<job>
<title><![CDATA[cleaner]]></title>
<description><![CDATA[cleaner in af]]></description>
<text><![CDATA[cleaner weekly in af]]></text>
<referencenumber><![CDATA[518]]></referencenumber>
<company><![CDATA[we q.]]></company>
<country_code><![CDATA[NL]]></country_code>
<city><![CDATA[af]]></city>
<url><![CDATA[url]]></url>
</job>
</jobs>
builder = Nokogiri::XML::Builder.new(:encoding => 'UTF-8') do |xml|
xml.jobs {
data.each do |data|
xml.job {
xml.title {
xml.cdata "..."
}
xml.text {
xml.cdata "..."
}
end
}
end
以上方法无效,因为 text
是构建器上的现有方法。
如何创建 <text>...</text>
节点?
来自docs:
The builder works by taking advantage of method_missing. Unfortunately some methods are defined in ruby that are difficult or dangerous to remove. You may want to create tags with the name “type”, “class”, and “id” for example. In that case, you can use an underscore to disambiguate your tag name from the method call.
附加下划线也适用于“文本”,即使用 text_
代替:
builder = Nokogiri::XML::Builder.new(:encoding => 'UTF-8') do |xml|
xml.job {
xml.text_ {
xml.cdata 'foo bar baz'
}
}
end
puts builder.to_xml
输出:
<?xml version="1.0" encoding="UTF-8"?>
<job>
<text><![CDATA[foo bar baz]]></text>
</job>
我需要这样xml:
<jobs>
<job>
<title><![CDATA[cleaner]]></title>
<description><![CDATA[cleaner in af]]></description>
<text><![CDATA[cleaner weekly in af]]></text>
<referencenumber><![CDATA[518]]></referencenumber>
<company><![CDATA[we q.]]></company>
<country_code><![CDATA[NL]]></country_code>
<city><![CDATA[af]]></city>
<url><![CDATA[url]]></url>
</job>
</jobs>
builder = Nokogiri::XML::Builder.new(:encoding => 'UTF-8') do |xml|
xml.jobs {
data.each do |data|
xml.job {
xml.title {
xml.cdata "..."
}
xml.text {
xml.cdata "..."
}
end
}
end
以上方法无效,因为 text
是构建器上的现有方法。
如何创建 <text>...</text>
节点?
来自docs:
The builder works by taking advantage of method_missing. Unfortunately some methods are defined in ruby that are difficult or dangerous to remove. You may want to create tags with the name “type”, “class”, and “id” for example. In that case, you can use an underscore to disambiguate your tag name from the method call.
附加下划线也适用于“文本”,即使用 text_
代替:
builder = Nokogiri::XML::Builder.new(:encoding => 'UTF-8') do |xml|
xml.job {
xml.text_ {
xml.cdata 'foo bar baz'
}
}
end
puts builder.to_xml
输出:
<?xml version="1.0" encoding="UTF-8"?>
<job>
<text><![CDATA[foo bar baz]]></text>
</job>