XScript Manual · Chapter 35

XML Object — Building and Reading XML Documents

XML is a collection of functions for building and reading XML documents. Each document is kept in memory under a name (xmlName), and an element is addressed with a path (path). Attributes are handled with a path plus an attribute name (attributeName).

  • Documents are stored by name in one place shared by all modules. Use names that do not clash with other modules, and remove documents you no longer need with Remove. All documents are removed when a project is opened.
  • A failed call leaves an error flag on that document. Check it with GetResult and read the details with GetErrorMessage. Unlike JSON, reading a missing element also sets the error flag.

Path notation

An XML path starts with the root element name and joins element names with /.

NotationMeaningExample
root/child/grandchildJoined with / starting from the root elementRecipe/Camera/Light
name:nElement n among siblings of the same name (from 0)Recipe/Items/Item:2
name (no index)The first of the siblings with that nameRecipe/Items/Item
  • Do not start a path with /. A path that starts with / points to the root element itself, so for example XML.SetString("doc", "/Recipe/Title", "A") replaces the entire content of the root with A (on an empty document, AddNode fails).
  • An index cannot be written in brackets such as Item[1] (error flag).
  • On an empty document (right after Create), the first name of the first path written becomes the root element.
  • If the first name differs from the root name, the element is looked up or created under the root (Title is the same as Recipe/Title). However, :n indexes cannot be used in a path without the root name, so always start paths with the root name.

Example

Creating a settings file

xscript
XML.Create("set");                                       // empty document ( no root )
XML.SetInteger("set", "Settings/Light", 70);             // the first name, Settings, becomes the root element
XML.SetDouble("set", "Settings/Exposure", 18.5);
XML.SetBool("set", "Settings/UseAuto", true);
XML.SetStringAttribute("set", "Settings", "version", "2");
XML.Save("set", "D:\\Settings\\vision.xml");
XML.Remove("set");

Saved file:

xscript
<?xml version="1.0" encoding="utf-8"?>
<Settings version="2">
  <Light>70</Light>
  <Exposure>18.5</Exposure>
  <UseAuto>True</UseAuto>
</Settings>

Several elements with the same name

xscript
XML.Create("lot");
XML.AddNode("lot", "Lot/Items/Item", "A01");                      // creates Lot and Items, then adds Item
XML.AddNode("lot", "Lot/Items/Item", "A02");                      // same path → one more Item ( sibling )
XML.SetIntegerAttribute("lot", "Lot/Items/Item:0", "count", 3);
XML.SetIntegerAttribute("lot", "Lot/Items/Item:1", "count", 5);
 
int n = XML.GetCount("lot", "Lot/Items", "Item");                 // 2
for(i, 0, n - 1)
{
   string name = XML.GetString("lot", $"Lot/Items/Item:{i}");
   int count = XML.GetInteger("lot", $"Lot/Items/Item:{i}", "count");
   Log("{0} = {1}", name, count);                                 // A01 = 3, A02 = 5
}
XML.Remove("lot");

Resulting document:

xscript
<Lot>
  <Items>
    <Item count="3">A01</Item>
    <Item count="5">A02</Item>
  </Items>
</Lot>

Reading XML produced by another program

xscript
FUNCTION bool LoadReport(string filePath)
{
   XML.Create("rep");                      // creating the name first turns a Load failure into an error flag
   XML.Load("rep", filePath);
   if( XML.GetResult("rep") == false )
   {
      LogError("report load failed : {0}", XML.GetErrorMessage("rep"));
      XML.Remove("rep");
      return false;
   }
   int n = XML.GetCount("rep", "Report/Items", "Item");
   for(i, 0, n - 1)
   {
      string name = XML.GetString("rep", $"Report/Items/Item:{i}/Name");
      int count = XML.GetInteger("rep", $"Report/Items/Item:{i}/Count");
      Log("#{0} {1} = {2}", i, name, count);
   }
   XML.Remove("rep");
   return true;
}

File being read:

xscript
<Report>
  <Items>
    <Item><Name>A01</Name><Count>3</Count></Item>
    <Item><Name>A02</Name><Count>5</Count></Item>
  </Items>
</Report>

Calling Load with a new name raises a runtime error if the file does not exist or is not XML, so create the name with Create first.

Reading several values and checking once

xscript
XML.Create("set");
XML.Load("set", "D:\\Settings\\vision.xml");
int light = XML.GetInteger("set", "Settings/Light");            // 0 if missing
double exposure = XML.GetDouble("set", "Settings/Exposure");    // 0.0 if missing
bool useAuto = XML.GetBool("set", "Settings/UseAuto");          // false if missing
if( XML.GetResult("set") == false )                             // false if the file could not be read, a value is missing, or not a number
{
   LogError("settings error : {0}", XML.GetErrorMessage("set"));   // last error message
}
XML.Remove("set");

Methods

Create · load · save

MethodDescription
void Create(string xmlName)Creates an empty document (no root). If the name already exists, it is replaced with a new empty document and the error flag is cleared.
void Parse(string xmlName, string xmlString)Reads an XML string into a document. On success it replaces any document of the same name. On failure, an existing name keeps its previous document and gets an error flag; a new name raises a runtime error.
void Load(string xmlName, string path)Reads an XML file into a document. Failure behaves the same as Parse.
void Save(string xmlName, string path)Saves the document as an indented UTF-8 file. The first line is the declaration <?xml version="1.0" encoding="utf-8"?>. If it cannot be saved (for example, the folder does not exist), an error flag is set. An unknown document name raises a runtime error.

Document management

MethodDescription
bool Contains(string xmlName)true if a document with that name exists.
void Remove(string xmlName)Removes the document. No error for an unknown name.
void RemoveAll()Removes every document, including documents used by other modules.

Checking results

MethodDescription
bool GetResult(string xmlName)true if the document exists and has no error flag.
string GetErrorMessage(string xmlName)Returns the last error message. "XmlManager not found." for an unknown name.
void ResetResult(string xmlName)Clears the error flag and message. The error flag is cleared only by this function, Create, or a successful Parse / Load.

Adding elements

MethodDescription
bool AddNode(string xmlName, string path, string value)Adds the last element of the path and sets its text to value. If an element at that path already exists, another sibling with the same name is added after it. Missing elements along the path are created. If the path is only the root ("Recipe"), only the root is created and value is not written. Returns false with an error flag on failure; an unknown document name raises a runtime error.
bool AddNodeCDATA(string xmlName, string path, string value)Same as AddNode, but the text is written as CDATA (<![CDATA[...]]>). Use it to keep strings containing < or & as they are.

Writing values

All of these return true on success. Missing elements are created before writing, and without an index the first sibling with that name is written. If a :n index exceeds the actual number of elements, false is returned with an error flag. For an unknown document name nothing is done and false is returned. Writing an element's text replaces the element's entire content, so writing to an element that has child elements removes them.

MethodDescription
bool SetString(string xmlName, string path, string value)Writes the element text.
bool SetInteger(string xmlName, string path, int value)Writes an integer as the element text.
bool SetDouble(string xmlName, string path, double value)Writes a real number as the element text.
bool SetBool(string xmlName, string path, bool value)Writes the element text as True / False.
bool SetStringCDATA(string xmlName, string path, string value)Writes the element text as CDATA.
bool SetStringAttribute(string xmlName, string path, string attributeName, string value)Writes an attribute value of the element. The attribute is added if it does not exist.
bool SetIntegerAttribute(string xmlName, string path, string attributeName, int value)Writes an integer attribute value.
bool SetDoubleAttribute(string xmlName, string path, string attributeName, double value)Writes a real-number attribute value.
bool SetBoolAttribute(string xmlName, string path, string attributeName, bool value)Writes a bool attribute value.

Reading values

Omit attributeName to read the element text, or pass it to read that attribute's value. If the element or attribute does not exist, or the value cannot be converted to the type, the default value ("", 0, 0.0, false) is returned and an error flag is set.

MethodDescription
string GetString(string xmlName, string path, string attributeName="")Reads as a string. For an element with child elements, the result is all the text inside it joined together.
int GetInteger(string xmlName, string path, string attributeName="")Reads as an integer.
double GetDouble(string xmlName, string path, string attributeName="")Reads as a real number.
bool GetBool(string xmlName, string path, string attributeName="")Reads true / false, case-insensitive.
int GetCount(string xmlName, string path, string childElementName="")Returns the number of child elements. With childElementName, only children with that name are counted. Returns 0 with an error flag if the element does not exist.

Notes

When the document name does not exist

FunctionBehavior
Value-reading functions · GetCountReturn "" · 0 · 0.0 · false.
Value-writing functions (SetString, etc.)Do nothing and return false.
GetResult · GetErrorMessageReturn false · "XmlManager not found.".
RemoveDoes nothing.
AddNode · AddNodeCDATA · Save · Parse · Load (on failure)Runtime error — execution stops at that point.

Other notes

  • Save writes UTF-8 with a BOM.
  • Arguments with default values (attributeName, childElementName) can be omitted. Function names are case-sensitive, and a call to an unknown name or with the wrong number of arguments is reported as a build error (Compile diagnostics).
Subscribe