问题
Nokogiri saves XML attributes with double quotes, even if DOM it read had single quotes. This is totally legitimate of course, but it introduces annoying changes to file contents even when DOM didn't change, making it harder for tools like diff and git to figure out what happened.
Can I force it to use single quotes (or even better, keep whatever quoting style there was in the original if nothing was modified)?
REXML has this for setting single/double quote:
doc.context[:attribute_quote] = :quote
I couldn't find anything similar for nokogiri.
Is it possible to have it save documents with single quotes?
回答1:
It looks like the answer is no; not as the library is currently written, and maybe not at all. Tracing the call path for a node's serialization:
Nokogiri::XML::Node#to_s
callsto_xml
Nokogiri::XML::Node#to_xml
callsserialize
(sets a few default options)Nokogiri::XML::Node#serialize
callswrite_to
Nokogiri::XML::Node#write_to
callsnative_write_to
Nokogiri::XML::Node#native_write_to
callsnative_write_to
, which looks like this:
&bsp;
def native_write_to(io, encoding, indent_string, options)
set_xml_indent_tree_output 1
set_xml_tree_indent_string indent_string
savectx = LibXML.xmlSaveToIO(IoCallbacks.writer(io), nil, nil, encoding, options)
LibXML.xmlSaveTree(savectx, cstruct)
LibXML.xmlSaveClose(savectx)
io
end
So, you are at the mercy of libxml at this point. Googling for libxml serialize single quote attributes does not immediately turn up any smoking guns.
I think you should file a feature request and see what sort of tenderlovin' you can get. :)
来源:https://stackoverflow.com/questions/4822922/can-nokogiri-use-single-quotes-for-attributes-on-saving-xml