2012-09-21 37 views
6

我需要生成一个XML的饲料看起来大致是这样的Ruby的RSS提要: -命名空间前缀和CDATA标签on Rails的

<?xml version="1.0" encoding="iso-8859-1" ?> 
<rss version="2.0" xmlns:g="http://base.google.com/ns/1.0" xmlns:atom="http://www.w3.org/2005/Atom"> 
<channel> 
    <item> 
     <g:id><![CDATA[id]]></g:id> 
     <title><![CDATA[Product Name]]></title> 
     <description><![CDATA[This should be a relatively detailed description with as little formatting as possible.]]></description> 
     <g:brand>Brand X</g:brand> 
     <g:sale_id>new</g:sale_id> 
    </item> 
    <item> 
     Next product... 
    </item> 
</channel> 
</rss> 

我的代码目前看起来是这样的: -

xml=Builder::XmlMarkup.new(:indent => 3) 
xml.instruct! 
xml.rss("version" => "2.0" , "xmlns:g" => "http://base.google.com/ns/1.0" , "xmlns:atom" => "http://www.w3.org/2005/Atom"){ 
xml.channel{ 
# remove xml.namespace = xml.namespace_definitions.find{|ns|ns.prefix=="atom"} 
sale_products.each do |sp| 
    sid = (products_info[sp.product_id]["sale_id"]).to_s() 
    xml.item { 
    #xml.id{ |xml| xml.cdata!(products_info[sp.product_id].own_id) } 
    #xml.g :id,{ xml.cdata!("sdaf") } 
    xml.product_title{ |xml| xml.cdata!(products_info[sp.product_id].name) } 
    xml.description{ |xml| xml.cdata!(ActionController::Base.helpers.strip_tags(products_info[sp.product_id].description)) } 
    xml.item { 
     xml.brand { |xml| xml.cdata!(products_info[sp.product_id].designer_1) } 
     xml.sale_id{ |xml| xml.cdata!(sid) } 
    } 
    } 

end 
} 
} 

我的问题是要同时获取命名空间前缀和cdata标签。

xml.g :id, "fdsafsad" 

这会得到namesapce前缀。

xml.product_title{ |xml| xml.cdata!(products_info[sp.product_id].name) } 

这会得到围绕值的cdata标签。

xml.g :id,{ xml.cdata!("sdaf") } 

这没有办法。

如何获得命名空间前缀以及同一个标记同时工作的cdata标记。我究竟做错了什么?

编辑: - 是我目前得到的输出是这样的: -

<g:id> 
    <![CDATA[10005-0003]]> 
</g:id> 

,我想应该只是CDATA标签内的值(不换行等)输出: -

<g:id><![CDATA[10005-0003]]></g:id> 

请注意,我不想在创建标记时删除:indent => 3,以便根据需要格式化其他标记。

+0

你能否详细说一下“没有做到这一招” - 它实际上做了什么?有错误吗?它产生了什么输出? – LarsH

+0

另外,为什么在':id'后面加逗号? – LarsH

+0

是的,这是一个错误。 –

回答

8
xml.tag!("g:id") { xml.cdata!("sdaf") } 
+0

将cdata封闭的值放在大括号内,可以确保这些值按照xml头缩进值缩进并放在新行中。同时可能没有这些值的缩进。 是否有可能具有像“<![CDATA [your-product-id-1234]]>”的值,尽管我在创建xml标记时指定了indent => someValue。 –

+0

对不起,我没有关注。你会发布一个例子,显示1)你目前得到的输出,2)你想要的输出? –

+0

Patrick,您可能需要通知@ user523146,以便他能看到您的评论。 – LarsH