XML
Reading, changing and writing XML documents.
x has its own XML parser, written in x. PureBasic uses expat, and x answers as expat does: the same status codes, error messages, lines and positions. The document tree, the text written out, FormatXML and Insert/Extract are compatible with PureBasic 6.50.
- Like expat, x doesn't validate against a DTD. A DTD is kept, whole, in a node of its own.
- Namespaces aren't resolved while parsing. Names such as
ns:itemstay as written;ResolveXMLNodeNameandResolveXMLAttributeNameresolve them. - An entity that the document's own DTD declares (
&me;) is kept as written, as PureBasic does. The five standard ones and character references (é,A) are turned into their characters.
Documents
CreateXML ✅, ParseXML ✅, LoadXML ✅, CatchXML ✅
Result = CreateXML(#XML [, Encoding])
Result = ParseXML(#XML, Input$)
Result = LoadXML(#XML, Filename$ [, Encoding])
Result = CatchXML(#XML, *Address, Size [, Flags [, Encoding]])
CreateXML makes an empty document (only its root node). The others read one.
-
Return value: as in PureBasic, the document is made even when the XML is broken. Returns nonzero unless there's no document at all (a file that can't be read). Check
XMLStatusto know whether the XML was right. -
What's kept on an error: the tree holds everything read up to the error.
-
Encoding (
#PB_UTF8,#PB_Ascii,#PB_Unicode) is the one used to save the document later.ParseXMLreads text, so its documents are#PB_Unicode.LoadXMLandCatchXMLtake the encoding from a byte-order mark, else from the XML declaration, else UTF-8, unless one is given.
-
In blocks:
CatchXMLcan read a document a block at a time (#PB_XML_StreamStart,#PB_XML_StreamNext, then#PB_XML_StreamEnd). After each block, the tree holds what has been read so far.x reads the whole document again for each block. So node values taken from the tree before the last block become invalid; take them again after it.
XMLStatus ✅, XMLError ✅, XMLErrorLine ✅, XMLErrorPosition ✅
Result = XMLStatus(#XML)
Result$ = XMLError(#XML)
Result = XMLErrorLine(#XML)
Result = XMLErrorPosition(#XML)
XMLStatus returns #PB_XML_Success (0) or an error code: #PB_XML_Syntax, #PB_XML_NoElements, #PB_XML_InvalidToken, #PB_XML_UnclosedToken, #PB_XML_TagMismatch, #PB_XML_DublicateAttribute, #PB_XML_JunkAfterDocElement, #PB_XML_UndefinedEntity, #PB_XML_BadCharacterRef, #PB_XML_UnclosedCDataSection, and so on (expat's codes, 0 to 40). XMLError gives expat's message for it, and the line and position (from 1) say where.
OpenConsole()
ParseXML(0, "<a>" + #LF$ + "<b x='1' x='2'/></a>")
PrintN(Str(XMLStatus(0)) + ": " + XMLError(0) + " at line " + Str(XMLErrorLine(0)) + ", position " + Str(XMLErrorPosition(0)))
Output:
8: duplicate attribute at line 2, position 10
FreeXML ✅, IsXML ✅
FreeXML(#XML)
Result = IsXML(#XML)
FreeXML(#PB_All) frees every document.
ComposeXML ✅, SaveXML ✅, ExportXML ✅, ExportXMLSize ✅
Result$ = ComposeXML(#XML [, Flags])
Result = SaveXML(#XML, Filename$ [, Flags])
Result = ExportXML(#XML, *Buffer, Size [, Flags])
Result = ExportXMLSize(#XML [, Flags])
The document as text, as a file, or as bytes in memory.
- The declaration:
ComposeXMLmakes a string, so its declaration always saysencoding="UTF-16". The others write the document's encoding and name it:UTF-8,UTF-16(little-endian) orISO-8859-1for#PB_Ascii, where characters above 255 become?. - Flags:
#PB_XML_NoDeclaration: no<?xml …?>.#PB_XML_StringFormat: a byte-order mark first (UTF-8 and UTF-16).
- What's escaped: in text,
&,<and>. In attribute values, those and",', tabs and line ends. - Empty elements: an element with no text and no children is written
<name/>. ExportXMLreturns the bytes written, or 0 ifSizeis too small.
FormatXML ✅
FormatXML(#XML, Flags [, IndentStep])
Tidies the document's white space before writing it. Any of:
| Flag | |
|---|---|
#PB_XML_ReFormat |
lays it out again: each element on its own line, indented by IndentStep (2 unless given) per level |
#PB_XML_ReIndent |
keeps the lines, and changes only the indentation |
#PB_XML_CutNewline / #PB_XML_ReduceNewline |
removes all line ends / only empty lines |
#PB_XML_CutSpace / #PB_XML_ReduceSpace |
removes all spaces / makes runs of spaces one (and removes them at the start of a line) |
#PB_XML_WindowsNewline, #PB_XML_LinuxNewline, #PB_XML_MacNewline |
makes every line end CR LF, LF or CR |
#PB_XML_ReFormat uses the line ends already in the document, or with none, the system's (CR LF on Windows).
OpenConsole()
ParseXML(0, "<list><item>one</item><item>two</item></list>")
FormatXML(0, #PB_XML_ReFormat | #PB_XML_LinuxNewline, 2)
PrintN(ComposeXML(0, #PB_XML_NoDeclaration))
Output:
<list>
<item>one</item>
<item>two</item>
</list>
GetXMLEncoding ✅, SetXMLEncoding ✅, GetXMLStandalone ✅, SetXMLStandalone ✅
Result = GetXMLEncoding(#XML)
SetXMLEncoding(#XML, Encoding)
Result = GetXMLStandalone(#XML)
SetXMLStandalone(#XML, Standalone)
Standalone: #PB_XML_StandaloneYes, #PB_XML_StandaloneNo (written into the declaration) or #PB_XML_StandaloneUnset (left out).
The tree
Nodes are values (pointers), as in PureBasic.
RootXMLNode ✅, MainXMLNode ✅, ChildXMLNode ✅, ParentXMLNode ✅, NextXMLNode ✅, PreviousXMLNode ✅, XMLChildCount ✅
Node = RootXMLNode(#XML)
Node = MainXMLNode(#XML)
Node = ChildXMLNode(Node [, Index])
Node = ParentXMLNode(Node)
Node = NextXMLNode(Node)
Node = PreviousXMLNode(Node)
Result = XMLChildCount(Node)
- The root node is the document itself. It holds the main element, together with any DTD, comments and processing instructions around it.
- The main node is the one top element.
- Children are counted from 1.
- A node that isn't there gives 0.
XMLNodeType ✅, GetXMLNodeName ✅, SetXMLNodeName ✅, GetXMLNodeText ✅, SetXMLNodeText ✅, GetXMLNodeOffset ✅, SetXMLNodeOffset ✅
Type = XMLNodeType(Node)
Name$ = GetXMLNodeName(Node)
SetXMLNodeName(Node, Name$)
Text$ = GetXMLNodeText(Node)
SetXMLNodeText(Node, Text$)
Offset = GetXMLNodeOffset(Node)
SetXMLNodeOffset(Node, Offset)
- Types:
#PB_XML_Root(0),#PB_XML_Normal(1),#PB_XML_Comment(2),#PB_XML_CData(3),#PB_XML_DTD(4),#PB_XML_Instruction(5).- Only normal nodes and instructions have names; an instruction's name is its target (
phpin<?php …?>).
- Text: a node's text is all its character data, with entities turned into characters.
- Each child's offset is how many of those characters come between it and the child before. So
<a>x<b/>yz<c/></a>has the textxyz,bat offset 1 andcat offset 2. - Changing the offsets moves text around the children.
- Each child's offset is how many of those characters come between it and the child before. So
XMLNodePath ✅, XMLNodeFromPath ✅, XMLNodeFromID ✅
Path$ = XMLNodePath(Node [, ParentNode])
Node = XMLNodeFromPath(ParentNode, Path$)
Node = XMLNodeFromID(#XML, ID$)
- Paths name each step:
/zoo/animal[2]is the secondanimalinzoo. - Special names:
#comment,#cdata,#dtd,#instruction, and*for any node. - Where a path starts: from the root if it starts with
/, otherwise fromParentNode. - By ID:
XMLNodeFromIDfinds the element whoseidattribute isID$.
OpenConsole()
x$ = "<zoo><animal kind='cat'>Tom</animal><animal kind='dog'>Rex</animal></zoo>"
If ParseXML(0, x$) And XMLStatus(0) = #PB_XML_Success
*a = XMLNodeFromPath(MainXMLNode(0), "animal[2]")
PrintN(GetXMLNodeText(*a) + " is a " + GetXMLAttribute(*a, "kind") + " at " + XMLNodePath(*a))
*c = ChildXMLNode(MainXMLNode(0))
While *c
PrintN(GetXMLNodeName(*c) + ": " + GetXMLNodeText(*c))
*c = NextXMLNode(*c)
Wend
EndIf
Output:
Rex is a dog at /zoo/animal[2]
animal: Tom
animal: Rex
Attributes: GetXMLAttribute ✅, SetXMLAttribute ✅, RemoveXMLAttribute ✅, ExamineXMLAttributes ✅, NextXMLAttribute ✅, XMLAttributeName ✅, XMLAttributeValue ✅
Value$ = GetXMLAttribute(Node, Attribute$)
SetXMLAttribute(Node, Attribute$, Value$)
RemoveXMLAttribute(Node, Attribute$)
Result = ExamineXMLAttributes(Node)
Result = NextXMLAttribute(Node)
Name$ = XMLAttributeName(Node)
Value$ = XMLAttributeValue(Node)
Attributes keep their order. A missing one reads as "".
CreateXMLNode ✅, CopyXMLNode ✅, MoveXMLNode ✅, DeleteXMLNode ✅
Node = CreateXMLNode(ParentNode, Name$ [, PreviousNode [, Type]])
Node = CopyXMLNode(Node, ParentNode [, PreviousNode])
Node = MoveXMLNode(Node, ParentNode [, PreviousNode])
DeleteXMLNode(Node)
- Where the node goes: first in
ParentNode(PreviousNode0, the default), last (-1), or afterPreviousNode. - Return value: returns 0 where the node can't go. That's when the root already has a main element and the new node would be another one, when
PreviousNodeisn't a child ofParentNode, or when a node would be moved into itself.
OpenConsole()
CreateXML(0)
*zoo = CreateXMLNode(RootXMLNode(0), "zoo")
*a = CreateXMLNode(*zoo, "animal", -1)
SetXMLAttribute(*a, "name", "Tom & Jerry")
SetXMLNodeText(*a, "a < b")
*c = CreateXMLNode(*zoo, "", -1, #PB_XML_Comment)
SetXMLNodeText(*c, " the end ")
PrintN(ComposeXML(0))
Output:
<?xml version="1.0" encoding="UTF-16"?><zoo><animal name="Tom & Jerry">a < b</animal><!-- the end --></zoo>
ResolveXMLNodeName ✅, ResolveXMLAttributeName ✅
Name$ = ResolveXMLNodeName(Node [, Separator$])
Name$ = ResolveXMLAttributeName(Node, Attribute$ [, Separator$])
ns:item, with xmlns:ns="http://example.com/ns" on it or an element around it, resolves to http://example.com/ns/item (or with another separator). An element without a prefix takes the default namespace (xmlns), if there is one.
Structures, arrays, lists and maps
InsertXMLStructure ✅, InsertXMLArray ✅, InsertXMLList ✅, InsertXMLMap ✅
Node = InsertXMLStructure(ParentNode, *Buffer, Structure [, PreviousNode])
Node = InsertXMLArray(ParentNode, Array() [, PreviousNode])
Node = InsertXMLList(ParentNode, List() [, PreviousNode])
Node = InsertXMLMap(ParentNode, Map() [, PreviousNode])
- InsertXMLStructure writes a node named like the structure (as written in its declaration), with a child per field. Field names lose
$and*. - Arrays, lists and maps become an
array,listormapnode. - Elements are
elementchildren; a map's carry akeyattribute. Their order is x's map order, which can differ from PureBasic's. - Fields that are collections or structures nest the same way.
ExtractXMLStructure ✅, ExtractXMLArray ✅, ExtractXMLList ✅, ExtractXMLMap ✅
ExtractXMLStructure(Node, *Buffer, Structure [, Flags])
ExtractXMLArray(Node, Array() [, Flags])
ExtractXMLList(Node, List() [, Flags])
ExtractXMLMap(Node, Map() [, Flags])
The way back.
- Before reading: the structure is cleared first, so a field with no node of its name ends up empty.
- Collections: arrays are resized to the number of
elementnodes. Map elements without akeyare left out, and other nodes are ignored. - Names: compared exactly unless
#PB_XML_NoCaseis given.
OpenConsole()
Structure Book
Title$
Pages.l
List Tags.s()
EndStructure
B.Book
B\Title$ = "XML for all" : B\Pages = 120
AddElement(B\Tags()) : B\Tags() = "new"
CreateXML(0)
InsertXMLStructure(RootXMLNode(0), @B, Book)
PrintN(ComposeXML(0, #PB_XML_NoDeclaration))
C.Book
ExtractXMLStructure(MainXMLNode(0), @C, Book)
PrintN(C\Title$ + ", " + Str(C\Pages) + " pages, " + Str(ListSize(C\Tags())) + " tag")
Output:
<Book><Title>XML for all</Title><Pages>120</Pages><Tags><element>new</element></Tags></Book>
XML for all, 120 pages, 1 tag