XML Sample Program
Posted: Sat Jun 02, 2007 2:46 pm
To learn about the new PureBasic XML library I wrote a small program to analyse an XML file that is based on the one shown at http://en.wikipedia.org/wiki/XML
I called the file XML Sample.txt and it contains:
My program which analyses this file is:
As it helped me, I am sharing my code in the hope it will also help other people.
I realise it can be improved by recursively traversing the XML tree, but at least it's a start.
I called the file XML Sample.txt and it contains:
Code: Select all
<book title="Mecanique" authors="Landau, Lifshitz">
<chapter title="equations du mouvement">
<section title="coordonnees generalisees">
Une des notions fondamentales de la Mecanique est celle de point materiel. ....
</section>
<section title="Le principe de moindre action">
La formule la plus generale de la loi du mouvement des systemes mecaniques est
fournie par le principe dit de moindre action (ou principe de Hamilton). ....
</section>
[Chapter 1 text]
</chapter>
<chapter title = "lois de conservation">
[Chapter 2 text]
</chapter>
[Book text]
</book>
Code: Select all
file$ = "XML Sample.txt"
Procedure ShowNode(label$, *node)
; Display node attributes and text
Protected tab$ = Space(4), text$
If *node
Debug label$+":"
Debug tab$+"Node name = "+GetXMLNodeName(*node)
ExamineXMLAttributes(*node)
While NextXMLAttribute(*node)
Debug tab$+XMLAttributeName(*node)+" = "+XMLAttributeValue(*node)
Wend
text$ = GetXMLNodeText(*node)
text$ = Trim(ReplaceString(text$, #CRLF$, " "))
Debug tab$+"Node text = "+text$
Debug tab$+"Child nodes = "+Str(XMLChildCount(*node))
EndIf
EndProcedure
tree = LoadXML(#PB_Any, file$)
Debug "Tree = "+Str(tree)
status = XMLStatus(tree)
Debug "Status = "+Str(status)
If status=0
*node = MainXMLNode(tree)
While *node
ShowNode("Parent", *node)
For child = 1 To XMLChildCount(*node)
*child = ChildXMLNode(*node, child)
ShowNode("Child "+Str(child), *child)
For grandchild = 1 To XMLChildCount(*child)
*grandchild = ChildXMLNode(*child, grandchild)
ShowNode("Grandchild "+Str(grandchild), *grandchild)
Next grandchild
Next child
*node = NextXMLNode(*node)
Wend
FreeXML(tree)
EndIf
End
I realise it can be improved by recursively traversing the XML tree, but at least it's a start.