问题
Here is the contents of my file (note the nested quotes):
<?xml version="1.0" encoding="utf-8"?>
<property name="eventData" value='{"key":"value"}'/>
in Ruby I have:
file = File.read(settings.test_file)
@xml = Nokogiri::XML( file)
puts "@xml " + @xml.to_s
and here is the output:
<property name="eventData" value="{"key":"value"}"/>
Is there a way to convert it so the output would preserve the quotes exactly? i.e. single on the outside, double on the inside?
回答1:
No, it cannot. There is no information stored in a Nokogiri::XML::Attr
(nor the underlying data structure in libxml2) about what type of quotes were (or should be) used to delimit an attribute. As such, all serialization (done by libxml2) uses the same attribute quoting style.
Indeed, this information is not even properly retained within the XML Information Set, as described by the specs:
Appendix D: What is not in the Information Set
The following information is not represented in the current version of the XML Information Set (this list is not intended to be exhaustive):
[...]
17) The kind of quotation marks (single or double) used to quote attribute values.
The good news is that the two XML serialization styles describe the exact same content. The bad news is that unless you're using a Canonical XML Serialization (which Nokogiri is not yet able to produce just recently able to produce) there are a large variety of ways to represent the same document that would look like many spurious 'changes' to a standard text-diffing tool.
Perhaps if you can describe why you wanted this functionality (what is the end goal you are trying to accomplish?) we could help you further.
You might also be interested in this similar question.
来源:https://stackoverflow.com/questions/8424858/can-nokogiri-retain-attribute-quoting-style