Generating XML with cdata using Ox?

血红的双手。 提交于 2019-12-23 02:47:30

问题


I need to generate XML using ox but didn't get much help from the documentation. I need to generate XML like this:

<Jobpostings>
  <Postings>
    <Posting>
      <JobTitle><cdata>Programmer Analyst 3-IT</cdata></JobTitle>
      <Location><cdata>Romania,Bucharest...</cdata></Location>
      <CountryCode><cdata>US</cdata>   </CountryCode>
      <JobDescription><cdata>class technology to develop.</cdata></JobDescription>             
    </Posting>     
  </Postings>
</jobpostings>

I have the data inside the tags as strings in variables like this:

jobtitle = "Programmer Analyst 3-IT" and so on...

I am currently using Nokogiri to generate XML but I need to work on large data, and, for the performance sake I am moving to Ox.

Any ideas on how to do this?


回答1:


It's pretty simple, you just initialize new elements and append them to other elements. Unfortunately there isn't an XML builder in the Ox library though... Here's an example:

require 'ox'
include Ox

source = Document.new

jobpostings = Element.new('Jobpostings')
source << jobpostings

postings = Element.new('Postings')
jobpostings << postings

posting = Element.new('Posting')
postings << posting

jobtitle = Element.new('JobTitle')
posting << jobtitle
jobtitle << CData.new('Programmer Analyst 3-IT')

location = Element.new('Location')
posting << location
location << CData.new('Romania,Bucharest...')

countrycode = Element.new('CountryCode')
posting << countrycode
countrycode << CData.new('US')
countrycode << '   '

jobdescription = Element.new('JobDescription')
posting << jobdescription
jobdescription << CData.new('class technology to develop.')

puts dump(source)

Returns:

<Jobpostings>
  <Postings>
    <Posting>
      <JobTitle>
        <![CDATA[Programmer Analyst 3-IT]]>
      </JobTitle>
      <Location>
        <![CDATA[Romania,Bucharest...]]>
      </Location>
      <CountryCode>
        <![CDATA[US]]>   </CountryCode>
      <JobDescription>
        <![CDATA[class technology to develop.]]>
      </JobDescription>
    </Posting>
  </Postings>
</Jobpostings>


来源:https://stackoverflow.com/questions/14751804/generating-xml-with-cdata-using-ox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!