【问题标题】:How do I create XML using Nokogiri::XML::Builder with a hyphen in the element name?如何使用 Nokogiri::XML::Builder 在元素名称中带有连字符来创建 XML?
【发布时间】:2010-12-29 04:07:54
【问题描述】:

我正在尝试使用 Nokogiri 构建 XML 文档。一些元素中有连字符。这是一个例子:

require "nokogiri"
builder = Nokogiri::XML::Builder.new do |xml|
  xml.foo_bar "hello"
end

puts builder.to_xml

产生:

<?xml version="1.0"?>
<foo_bar>hello</foo_bar>

但是,当我尝试时:

builder = Nokogiri::XML::Builder.new do |xml|
  xml.foo-bar "hello"
end

我明白了:

syntax error, unexpected tSTRING_BEG, expecting kDO or '{' or '('
  xml.foo-bar "hello"

现在我意识到这是因为连字符被解释为foo MINUS bar

我应该怎么做?

【问题讨论】:

    标签: xml ruby nokogiri


    【解决方案1】:

    给你:

    require 'nokogiri'
    
    b = Nokogiri::XML::Builder.new do |xml|
      xml.send(:"fooo-bar", "hello")
    end
    
    puts b.to_xml
    

    【讨论】:

    • 你好从哪里来的? xml.send(:"foo-bar", "hello")?
    • Nokogiri 官方文档在哪里记录?可以分享一下链接吗?
    • 在这里聚会有点晚了,但是 :"xx-aaa" 语法是标准的 Ruby 语法,当语法不适合你的时候
    【解决方案2】:

    Bart Vandendriessche 的回答有效,但如果您只想要元素中的文本字段,还有一个更简单的解决方案。

    require 'nokogiri'
    
    b = Nokogiri::XML::Builder.new do |xml|
      xml.send(:"foo-bar", 'hello')
    end
    
    puts b.to_xml
    

    生成:

    <?xml version="1.0"?>
    <foo-bar>hello</foo-bar>
    

    如果你需要它们嵌套,那么你可以传递一个块

    require 'nokogiri'
    
    b = Nokogiri::XML::Builder.new do |xml|
      xml.send(:'foo-bar') {
        xml.send(:'bar-foo', 'hello')
      }
    end
    
    puts b.to_xml
    

    生成:

    <?xml version="1.0"?>
    <foo-bar>
      <bar-foo>hello</bar-foo>
    </foo-bar>
    

    【讨论】:

      【解决方案3】:

      Aaron Patterson 的回答是正确的,并且适用于包含任何可能被 Ruby 解析器解释的字符的元素名称。

      回答安吉拉的问题:将文本放置在以这种方式创建的元素中,您可以执行以下操作:

      require 'rubygems'
      require 'nokogiri'
      
      b = Nokogiri::XML::Builder.new do |xml|
        xml.send(:'foo.bar') {
          xml.text 'hello'
        }
      end
      
      puts b.to_xml
      

      【讨论】:

        猜你喜欢
        • 2012-04-23
        • 1970-01-01
        • 1970-01-01
        • 2010-12-22
        • 1970-01-01
        • 2015-04-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多