简体   繁体   中英

Namespace prefix and cdata tags in xml generation for rss feed in Ruby on Rails

I need to generate an xml for a feed which looks roughly like this :-

    <?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>

My code currently looks something like this :-

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
}
}

My problem is around getting both namespace prefixes and cdata tags working at the same time.

xml.g :id, "fdsafsad"

This gets the namesapce prefix.

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

This gets cdata tags around the values.

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

This fails to do the trick.

How do i get both the namespace prefix as well as the cdata tags working at the same time for the same tag. What am I doing wrong?

Edit :- The output that I am currently getting is like:-

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

The output that I want should just have the value inside cdata tags (no newline etc) :-

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

Note that I do not want to remove the :indent => 3 while creating the markup, so that other tags are formatted as required.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM