ExtractXMLStructure with CDATA

Just starting out? Need help? Post your questions and find answers here.
wayne-c
Enthusiast
Enthusiast
Posts: 335
Joined: Tue Jun 08, 2004 10:29 am
Location: Zurich, Switzerland

ExtractXMLStructure with CDATA

Post by wayne-c »

Hello PB community

Any ideas or workarounds to read node values with CDATA?

Code: Select all

Structure Person
	Name$
	Age.l
	Test$
EndStructure

; this runs fine:
;XML$ = "<Person><Name>John Deere</Name><Age>41</Age><Test>Hello World</Test></Person>"

; this can not be read (CDATA)
XML$ = "<Person><Name>John Deere</Name><Age>41</Age><Test><![CDATA[<b>Hello World</b>!]]></Test></Person>"

If ParseXML(0, XML$) And XMLStatus(0) = #PB_XML_Success
	Define P.Person
	ExtractXMLStructure(MainXMLNode(0), @P, Person)
	Debug P\Name$
	Debug P\Age
	Debug P\Test$
Else
	Debug XMLError(0)
EndIf
Thank you!
As you walk on by, Will you call my name? Or will you walk away?
User avatar
kenmo
Addict
Addict
Posts: 1967
Joined: Tue Dec 23, 2003 3:54 am

Re: ExtractXMLStructure with CDATA

Post by kenmo »

You could convert CData nodes to "normal" node text...

I'm not sure if this will work in all cases!

Code: Select all

Structure Person
   Name$
   Age.l
   Test$
EndStructure

; this runs fine:
;XML$ = "<Person><Name>John Deere</Name><Age>41</Age><Test>Hello World</Test></Person>"

; this can not be read (CDATA)
XML$ = "<Person><Name>John Deere</Name><Age>41</Age><Test><![CDATA[<b>Hello World</b>!]]></Test></Person>"

Procedure FormatCData(XML, *Node = #Null)
  If (*Node)
    *Child = ChildXMLNode(*Node)
    While (*Child)
      *Next = NextXMLNode(*Child)
      If (XMLNodeType(*Child) = #PB_XML_CData)
        SetXMLNodeText(*Node, GetXMLNodeText(*Child))
        DeleteXMLNode(*Child)
      ElseIf (XMLNodeType(*Child) = #PB_XML_Normal)
        FormatCData(XML, *Child)
      EndIf
      *Child = *Next
    Wend
  Else
    FormatCData(XML, MainXMLNode(XML))
  EndIf
EndProcedure

If ParseXML(0, XML$) And XMLStatus(0) = #PB_XML_Success
  
  FormatCData(0) ; <---------
  
   Define P.Person
   ExtractXMLStructure(MainXMLNode(0), @P, Person)
   Debug P\Name$
   Debug P\Age
   Debug P\Test$
Else
   Debug XMLError(0)
EndIf
wayne-c
Enthusiast
Enthusiast
Posts: 335
Joined: Tue Jun 08, 2004 10:29 am
Location: Zurich, Switzerland

Re: ExtractXMLStructure with CDATA

Post by wayne-c »

@ kenmo Thank you, this works like a charm! I first was a bit worried about speed when I did see your response with crawling through the full XML tree and making modifications, but for the file sizes I am using it seems to be fast enough - actually it is pretty fast (0,001 secs) :-)
As you walk on by, Will you call my name? Or will you walk away?
Post Reply