【问题标题】:Transforming XML structures using Ruby使用 Ruby 转换 XML 结构
【发布时间】:2014-04-04 20:57:18
【问题描述】:

我一直在绞尽脑汁试图解决这个问题。这是我第一次使用任何脚本语言来完成这类工作,我想我一开始可能选择了一份艰巨的工作。本质上,我需要做的是将一些基本的 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,但不知道如何正确使用它们。

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

【问题讨论】:

    标签: xml ruby transformation


    【解决方案1】:

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

    【讨论】:

    • 查看来自oxygenxml.com 的 Oxygen 以获得一个很好实现的 XSLT IDE。它具有专业 IDE 所具备的所有调试功能,可以真正快速开始学习过程。
    【解决方案2】:
    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
    

    标签之间不会有空格

    【讨论】:

      【解决方案3】:

      Hpricot 和 Builder 的组合可以满足您的需求。步骤是:

      1. 使用 Hpricot 读取 XML
      2. 挑选你想要的元素
      3. 通过迭代 Hpricot 中的元素来生成新的 XML(通过 Builder)

      【讨论】:

      • 我也会调查一下。谢谢。
      猜你喜欢
      • 2013-01-14
      • 2011-01-17
      • 1970-01-01
      • 2011-04-08
      • 2012-05-31
      • 1970-01-01
      • 1970-01-01
      • 2010-11-02
      • 1970-01-01
      相关资源
      最近更新 更多