xmlexcelvbaxmldocumentcdata

How to create CDATA tag in Excel vba?


Can anyone please help.

I am trying to convert excel data into xml file uisng vba. My xml file looks like this,

 <product>
  <info><i>Samsung</i></info>
 </product>

I want the html tags not to be parsed.so trying to add cdata in vba using createCDATASection method in vba

I added vba code like this

  Set objDom = New DOMDocument
  Set objXMLRootelement = objDom.createElement("Product")
  Set objXMLelement = objDom.createElement("info")
  objXMLRootelement.appendChild objXMLelement
  cdata=objDom.createCDATASection ("<i>Samsung</i>")
  objXMLelement.text=cdata.text

I want my xml file to appear like this and when viewed the viewsource in notepad it should
display '<' as '<' but not 'ampersand lt;'

  <product>
    <info><![CDATA[<i>Samsung</i>]]></info>
  </product>

after executing my code it is displaying like this,

  <product>
   <info><i>Samsung</i></info>
  </product>

but cdata tag is not appearing.Dont know the reason.And when viewed the view source of the xml file in notepad '<' symbol is shown as ampersand lt;

can anyone please solve this?

Thanks in advance


Solution

  • Try this

    Sub zx()
        Dim objDom As DOMDocument
        Dim objXMLRootelement As IXMLDOMElement
        Dim objXMLelement As IXMLDOMElement
        Dim cdata As IXMLDOMCDATASection
    
        Set objDom = New DOMDocument
        Set objXMLRootelement = objDom.createElement("Product")
        objDom.appendChild objXMLRootelement
        Set objXMLelement = objDom.createElement("info")
        objXMLRootelement.appendChild objXMLelement
        Set cdata = objDom.createCDATASection("info")
        cdata.Data = "<i>Samsung</i>"
        objXMLelement.appendChild cdata
    
        Debug.Print objDom.XML
    End Sub