1

我一直在绞尽脑汁试图解决这个问题。这是我第一次使用任何脚本语言来完成这类工作,我想我一开始可能选择了一份艰巨的工作。本质上,我需要做的是将一些基本的 XML 转换为更重的 XML 结构。

例子 :

翻译以下内容:

<xml>
  <test this="stuff">13141</test>
  <another xml="tag">do more stuff</another>
<xml>

进入这个:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE Package>
<Package version="1.0">
  <tests>
    <test name="stuff">
      <information>13141</information>
    </test>
  </tests>
  <anothers>
    <another name="tag">
      <information>do more stuff</information>
    </another>
  </anothers>
</Package>

我试过通过正则表达式手动完成,但这是很多工作要做。例如,我尝试将多个测试标签存储到一个数组中,因此我可以将它们保存到第二个示例中的测试标签中,但我似乎无法跟踪所有内容。我研究了 REXML 和 Hpricot,但不知道如何使用它们来正确执行此操作。

所以,基本上,我要问的是:有没有人对我如何能够以更有效的方式管理它有任何想法?

4

3 回答 3

2

查看 XSLT。我对这项技术只略知一二,但它的用途是将 XML 文档从一种形式转换为另一种形式,这听起来像是您所需要的。

于 2009-08-14T15:23:27.310 回答
1
require 'rubygems'
require 'hpricot'
require 'activesupport'

source = <<-XML
<xml>
<test this="stuff">13141</test>
<another xml="tag">do more stuff</another>
</xml>
XML

def each_source_child(source)
  doc = Hpricot.XML(source)

  doc.at('xml').children.each do |child|
    if child.is_a?(Hpricot::Elem)
      yield child
    end
  end
end

output = Hpricot.build do |doc|
  doc << '<?xml version="1.0" encoding="UTF-8"?>'
  doc << '<!DOCTYPE Package>'
  doc.tag! :Package, :version => '1.0' do |package|
    each_source_child(source) do |child|
      package.tag! child.name.pluralize do |outer|
        outer.tag! child.name, :name => child.attributes.values.first do |inner|
          inner.tag! :information do |information|
            information.text! child.innerText
          end
        end
      end
    end
  end
end

puts output

there will be no whitespaces between tags

于 2009-08-15T20:22:03.437 回答
0

Hpricot 和 Builder 的组合可以提供您正在寻找的东西。步骤是:

  1. 使用 Hpricot 读取 XML
  2. 挑选你想要的元素
  3. 通过迭代来自 Hpricot 的元素,吐出你的新 XML(通过 Builder)
于 2009-08-14T15:26:28.630 回答