将原始XML添加到使用libxml

编程入门 行业动态 更新时间:2024-10-24 01:53:52
原始XML添加到使用libxml-ruby构建的XML文档中(Add raw XML into XML document built with libxml-ruby)

使用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>&lt;Style&gt; &lt;foo&gt;bar&lt;/foo&gt; &lt;/Style&gt; </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_s

The result:

<?xml version="1.0" encoding="UTF-8"?> <Document>&lt;Style&gt; &lt;foo&gt;bar&lt;/foo&gt; &lt;/Style&gt; </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 << node

xml.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

更多推荐

本文发布于:2023-08-06 16:24:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1451934.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:原始   XML   libxml

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!