使用KML(当然是XML),我有很多样式 - 对于人类 - 最容易阅读和维护为原始XML。 我想将它们添加到使用libxml-ruby构建的XML文档中。
这是一个简化的例子:
require 'xml' raw_xml = <<~END <Style> <foo>bar</foo> </Style> END xml = XML::Document.new xml.root = XML::Node.new(:Document) xml.root << raw_xml xml.to_s结果:
<?xml version="1.0" encoding="UTF-8"?> <Document><Style> <foo>bar</foo> </Style> </Document>这是预料之中的,因为<<不解析原始XML。 但是,我的问题是有没有办法正确地做到这一点并获得以下输出?
<?xml version="1.0" encoding="UTF-8"?> <Document> <Style> <foo>bar</foo> </Style> </Document>谢谢你的提示!
Working with KMLs (which of course are XML), I have loads of styles which – for humans – are easiest to read and maintain as raw XML. I'd like to add those into a XML document being built with libxml-ruby.
Here's a simplified example:
require 'xml' raw_xml = <<~END <Style> <foo>bar</foo> </Style> END xml = XML::Document.new xml.root = XML::Node.new(:Document) xml.root << raw_xml xml.to_sThe result:
<?xml version="1.0" encoding="UTF-8"?> <Document><Style> <foo>bar</foo> </Style> </Document>That was to be expected since << does not parse the raw XML. My question, however, is there a way to do this right and get the the following output?
<?xml version="1.0" encoding="UTF-8"?> <Document> <Style> <foo>bar</foo> </Style> </Document>Thanks for your hints!
最满意答案
xml.root是LibXML::XML::Node一个实例,它的<< ,方法用于添加节点。 不用于解析XML字符串。
要解析字符串,可以使用例如XML::Parser.string :
xml = XML::Document.new xml.root = XML::Node.new(:Document) # Parse the string into XML::Document, then take its root node tree another_doc = XML::Parser.string(raw_xml).parse node = xml.import(another_doc.root) xml.root << nodexml.root is an instance of LibXML::XML::Node, its << ,method is for adding a node. Not for parsing XML string.
To parse a string, you can use for example XML::Parser.string:
xml = XML::Document.new xml.root = XML::Node.new(:Document) # Parse the string into XML::Document, then take its root node tree another_doc = XML::Parser.string(raw_xml).parse node = xml.import(another_doc.root) xml.root << node更多推荐
发布评论