我正在尝试使用合作伙伴提供给我的规范创建XML文档,并且我在创建指定的XML字段名称时遇到一些问题。我们通常创建字段名,这样输出就像下面的例子一样。
def build_xml(output_rows)
builder = Nokogiri::XML::Builder.new(:encoding => 'utf-8') do |xml|
xml.BATCH{
xml.HEADER{
xml.CBPosterEmail ("test@foo.com")
xml.CBPosterPassword ('123456')
xml.CBReplace ('Yes')
xml.CBReplyTo ('replytome@foo.com')
} #xml HEADER
<Header>
<CBEmail>test@foo.com</CBEmail>
<CBPosterPassword>123456</CBPosterPassword>
<CBReplace>Yes</CBReplace>
<CBReplyTo>replytome@foo.com</CBReplyTo>
</Header>
我需要让字段名出现在输出中,如下例所示:
<Header>
<Field name="CBPosterEmail" value="test@foo.com" />
<Field name="CBPosterPassword" value="123456" />
<Field name=”CbReplace” value=”Yes”>
<Field name=”CBReplyTo” value=”replytome@foo.com”>
</Header>
我得到一个错误,当我试图添加字段名称="和值=块。我是一个完全的Nokogiri新手,所以如果我听起来像一个完全的白痴,请原谅我。如有任何帮助,不胜感激。
require 'nokogiri'
builder = Nokogiri::XML::Builder.new(:encoding => 'utf-8') do |xml|
xml.batch {
xml.header {
xml.field(:name => "CBPosterEmail", :value => "test@foo.com")
xml.field(:name => "CBPosterPassword", :value => "123456")
xml.field(:name => "CBReplace", :value => "Yes")
xml.field(:name => "CBReplyTo", :value => "replytome@foo.com")
}
}
end
puts builder.to_xml
=> <?xml version="1.0" encoding="utf-8"?>
<batch>
<header>
<field name="CBPosterEmail" value="test@foo.com"/>
<field name="CBPosterPassword" value="123456"/>
<field name="CBReplace" value="Yes"/>
<field name="CBReplyTo" value="replytome@foo.com"/>
</header>
</batch>
请参阅Nokogiri的Builder文档中的"Tag attributes"部分。
builder = Nokogiri::XML::Builder.new(:encoding => 'utf-8') do |xml|
xml.BATCH{
xml.HEADER{
xml.Field( name: 'CBPosterEmail', value: 'test@foo.com' )
xml.Field( name: 'CBPosterPassword', value: '123456' )
xml.Field( name: 'CBReplace', value: 'Yes' )
xml.Field( name: 'CBReplyTo', value: 'replytome@foo.com' )
}
}
end
puts builder.to_xml
结果是:
<?xml version="1.0" encoding="utf-8"?>
<BATCH>
<HEADER>
<Field name="CBPosterEmail" value="test@foo.com"/>
<Field name="CBPosterPassword" value="123456"/>
<Field name="CBReplace" value="Yes"/>
<Field name="CBReplyTo" value="replytome@foo.com"/>
</HEADER>
</BATCH>
示例代码显示您正在尝试添加<BATCH>
标记,但是所需的输出示例没有显示它。如果输出示例正确,将生成如下内容:
builder = Nokogiri::XML::Builder.new(:encoding => 'utf-8') do |xml|
xml.HEADER{
xml.Field( name: 'CBPosterEmail', value: 'test@foo.com' )
xml.Field( name: 'CBPosterPassword', value: '123456' )
xml.Field( name: 'CBReplace', value: 'Yes' )
xml.Field( name: 'CBReplyTo', value: 'replytome@foo.com' )
}
end
结果是:
<?xml version="1.0" encoding="utf-8"?>
<HEADER>
<Field name="CBPosterEmail" value="test@foo.com"/>
<Field name="CBPosterPassword" value="123456"/>
<Field name="CBReplace" value="Yes"/>
<Field name="CBReplyTo" value="replytome@foo.com"/>
</HEADER>