Data Import
The Data Import window of ProB2-UI turns an external data file into a classical B machine that contains the data as B constants. The generated machine is opened directly in ProB2-UI, so the data can be inspected, queried with B expressions and validated, e.g. with rules machines.
Supported formats are XML (typed, via XML2B), XML (untyped), JSON, CSV and railML 3. The menu was introduced in ProB2-UI 1.3.1; the railML 3 import was added in ProB2-UI 1.4.0.
Overview
Section titled “Overview”All imports are started from the menu bar: Advanced > Data Import and then one of the following entries.
| Menu entry | Files | Backend | What the generated machine contains |
|---|---|---|---|
| XML | .xml (optionally with an .xsd schema) |
XML2B | A fully typed B representation of the XML tree. The data itself is stored in a separate .probdata file. |
| XML (untyped) | .xml |
LibraryXML.def (READ_XML) |
A single constant that is filled by the external function READ_XML whenever the constants are set up. |
| JSON | .json |
LibraryJSON (READ_JSON) |
A single constant of the free type JsonValue, filled by READ_JSON. |
| CSV | .csv |
LibraryCSV.def (READ_CSV) |
A single constant holding the rows of the file, filled by READ_CSV or READ_CSV_SEQUENCE. |
| railML 3 | .railml, .railmlx |
railML2B | See the separate article ProB for railML. |
An important difference between the formats:
- For XML (typed) the XML file is translated once, at import time. If the XML file changes, the import has to be repeated (see Update only Translated Data below). The same applies to railML 3.
- For XML (untyped), JSON and CSV the generated machine only contains the path of the data file and a call of an external function. The file is read every time the constants of the machine are set up, so after changing the data file it is sufficient to reload the machine. These machines contain the absolute path of the data file and are therefore not portable to another computer.
The Data Import window
Section titled “The Data Import window”All formats share the same window layout. Format specific options are listed below the common fields.
<format> File
The file to be imported. Use Select File… to choose it.
Output Location
The directory in which the machine is generated. This field is not filled automatically: choose a directory with Select Location… or click Same as File to use the directory of the imported file.
Custom Machine Name
By default the machine is named like the imported file without its extension (order.xml results in order.mch with MACHINE order). Tick the check box to choose another name. Names must not contain a dot, because dots are not allowed in B identifiers; for a file such as empty.dot.xml the dialog proposes empty_dot automatically.
Import + Open
Starts the import. When it has finished, the dialog closes and the generated machine is opened in ProB2-UI.
XML (typed, XML2B)
Section titled “XML (typed, XML2B)”The menu entry XML uses XML2B. XML2B reads the XML file (optionally validating it against an XSD schema) and derives a B type for every attribute value and every text content.
Options
Section titled “Options”Use Types from XSD Schema
If ticked, the XML file is validated against the chosen XSD file and the types of attributes and contents are taken from the schema. Without a schema the types are inferred from the values (see below).
Export with Prolog Fast-Read/Write Format
(ticked by default) The data file .probdata is written in the fast read/write format of SICStus Prolog, which can improve the loading time significantly. If unticked, the file contains the data as plain Prolog text. Use the fast format for large files.
Update only Translated Data (overwrite)
If ticked, only the .probdata file is regenerated. The machine .mch is neither rewritten nor opened. This is useful if the XML file has changed and other machines that refer to the generated machine should be kept; reload the machine afterwards.
Generated files
Section titled “Generated files”For an input file order.xml XML2B generates two files in the output location:
order.mch: the B machine with the type declarationsorder.probdata: the translated data
The machine refers to the data file by its file name only, so both files have to stay in the same directory (copy both when moving or sharing the machine).
Example without schema
Section titled “Example without schema”Input file order.xml:
<?xml version="1.0" encoding="UTF-8"?><order id="id_abc"> <customer name="Müller"> <item product="XMLFile1" version="1.0"/> </customer> <customer name="Paul"> <item product="XMLFile2"/> </customer></order>The generated machine order.mch has the following structure (reformatted; the layout of the generated file differs slightly):
MACHINE orderDEFINITIONS "LibraryProB.def"FREETYPES XML_ATTRIBUTE_TYPES = XmlString(STRING), XmlReal(REAL)CONSTANTS XML_DATAPROPERTIES XML_DATA = READ_PROB_DATA_FILE( seq(struct(maxCId: INTEGER, pIds: seq(INTEGER), recId: INTEGER, Element: STRING, ns: STRING, content: POW(XML_ATTRIBUTE_TYPES), attributes: STRING +-> XML_ATTRIBUTE_TYPES, xmlLocation: (INTEGER*INTEGER)*(INTEGER*INTEGER))), "order.probdata")ENDThe machine declares
- a free type
XML_ATTRIBUTE_TYPESwith one constructor for every B type that occurs in the file, - one constant
XML_DATA, whose value is read fromorder.probdata. The first argument ofREAD_PROB_DATA_FILErepeats the type of the data, so the machine can be type checked without reading the data.
After opening the machine and executing SETUP_CONSTANTS, XML_DATA has the following value:
[ rec(recId:1, pIds:[0], maxCId:5, Element:"order", ns:"", content:{}, attributes:{("id"|->XmlString("id_abc"))}, xmlLocation:(2|->20|->(9|->9))), rec(recId:2, pIds:[1], maxCId:3, Element:"customer", ns:"", content:{}, attributes:{("name"|->XmlString("Müller"))}, xmlLocation:(3|->29|->(5|->16))), rec(recId:3, pIds:[1,2], maxCId:3, Element:"item", ns:"", content:{}, attributes:{("product"|->XmlString("XMLFile1")),("version"|->XmlReal(1.0))}, xmlLocation:(4|->49|->(4|->49))), rec(recId:4, pIds:[1], maxCId:5, Element:"customer", ns:"", content:{}, attributes:{("name"|->XmlString("Paul"))}, xmlLocation:(6|->27|->(8|->16))), rec(recId:5, pIds:[1,4], maxCId:5, Element:"item", ns:"", content:{}, attributes:{("product"|->XmlString("XMLFile2"))}, xmlLocation:(7|->35|->(7|->35))) ]The data model
Section titled “The data model”XML_DATA is a sequence of records with one record for every XML element in document order. The record fields are:
| Field | Type | Meaning |
|---|---|---|
recId |
INTEGER |
Running number of the element in document order, starting at 1. It is also the index of the element in XML_DATA. |
pIds |
seq(INTEGER) |
The recIds of all ancestors from the root down to the parent. The last entry is the parent. The root element has [0]. |
maxCId |
INTEGER |
The highest recId in the subtree of the element (its own recId for an element without children). All descendants of an element e therefore have a recId between e'recId+1 and e'maxCId. |
Element |
STRING |
The local name of the element. The field name starts with a capital letter. |
ns |
STRING |
The namespace URI of the element, or the empty string. |
content |
POW(XML_ATTRIBUTE_TYPES) |
The text content of the element: a set with one element, or the empty set if there is no text. Surrounding white space is removed. |
attributes |
STRING +-> XML_ATTRIBUTE_TYPES |
The attributes of the element: a partial function from the attribute name to the typed value. Attributes that are absent in the XML file (and have no default value in the schema) are not in the domain. |
xmlLocation |
(INTEGER*INTEGER)*(INTEGER*INTEGER) |
Position in the XML file as reported by the XML parser: ((startLine,startColumn),(endLine,endColumn)). Useful to point to the origin of a rule violation. |
Attribute values and contents are wrapped in the constructors of XML_ATTRIBUTE_TYPES. Use the inverse constructor (see Free Types) to get the plain value, e.g. XmlString~(e'attributes("name")).
| Constructor | B type | Without schema (inferred from the value) | With XSD schema |
|---|---|---|---|
XmlString |
STRING |
everything that is not recognised as one of the types below | xs:string and similar string, date and time types |
XmlReal |
REAL |
every number, also integers ("20" becomes 20.0); ISO 8601 durations such as PT6S become milliseconds (6000.0) |
xs:decimal, xs:double, durations |
XmlInteger |
INTEGER |
never inferred | xs:int, xs:integer, xs:long, xs:short, … |
XmlBool |
BOOL |
the values true and false |
xs:boolean |
XmlFloat |
FLOAT |
never inferred | xs:float |
XmlSetName |
the enumerated set SetName | never inferred | named xs:enumeration restrictions |
Only the constructors for types that occur in the XML file (or, with a schema, in the schema) appear in the free type declaration. The complete mapping from XSD types to B types is documented in the README of XML2B.
Example with XSD schema: types
Section titled “Example with XSD schema: types”Without a schema, all numeric values are real numbers and a value like "20" is a REAL (XmlReal(20.0)). A schema fixes this. Consider this XML file and schema:
<school id="school01"> <student name="Anna" age="20"> <course title="Mathematik" credits="5"/> </student> <student name="Ben"> <course title="Informatik"/> </student></school><xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="school"> <xs:complexType> <xs:sequence> <xs:element name="student" maxOccurs="unbounded"> <xs:complexType> <xs:sequence> <xs:element name="course"> <xs:complexType> <xs:attribute name="title" type="xs:string" use="required"/> <xs:attribute name="credits" type="xs:int"/> </xs:complexType> </xs:element> </xs:sequence> <xs:attribute name="name" type="xs:string" use="required"/> <xs:attribute name="age" type="xs:int"/> </xs:complexType> </xs:element> </xs:sequence> <xs:attribute name="id" type="xs:string" use="required"/> </xs:complexType> </xs:element></xs:schema>Importing with Use Types from XSD Schema gives the free type XML_ATTRIBUTE_TYPES = XmlString(STRING), XmlInteger(INTEGER), and the student records look like this:
rec(recId:2, pIds:[1], maxCId:3, Element:"student", ns:"", content:{}, attributes:{("age"|->XmlInteger(20)),("name"|->XmlString("Anna"))}, ...)rec(recId:4, pIds:[1], maxCId:5, Element:"student", ns:"", content:{}, attributes:{("name"|->XmlString("Ben"))}, ...)The age of the second student is optional and absent in the file, so "age" is not in the domain of its attributes. Always test with "age" : dom(e'attributes) before applying e'attributes("age"). If the XML file does not conform to the schema (e.g. a wrong attribute type or a missing required attribute), the import fails and the validation errors are shown in the error dialog. Default and fixed values declared in the schema are added for attributes that are missing in the XML file.
Example with XSD schema: enumerations
Section titled “Example with XSD schema: enumerations”Enumerations in the schema become B enumerated sets. Schema (excerpt) and XML file:
<xs:simpleType name="StatusType"> <xs:restriction base="xs:string"> <xs:enumeration value="open"/> <xs:enumeration value="closed"/> <xs:enumeration value="pending"/> </xs:restriction></xs:simpleType><xs:element name="ticket"> <xs:complexType> <xs:attribute name="id" type="xs:string" use="required"/> <xs:attribute name="status" type="StatusType" use="required"/> </xs:complexType></xs:element><ticket id="T1" status="open"/>The machine now contains a SETS clause. The enumeration values are prefixed with the name of the set, and the free type gets a constructor named after the set:
SETS StatusType = {StatusType_open, StatusType_closed, StatusType_pending}FREETYPES XML_ATTRIBUTE_TYPES = XmlString(STRING), XmlStatusType(StatusType)attributes:{("id"|->XmlString("T1")),("status"|->XmlStatusType(StatusType_open))}An invalid value such as status="done" is rejected during the import. If a schema combines an enumeration with a xs:pattern (e.g. “standard values or custom-[A-Za-z0-9]+”), the enumerated set is extensible and values that match the pattern are added when the data is translated, e.g. XmlStatusType(`StatusType_custom-premium`).
Querying the XML data
Section titled “Querying the XML data”Open the generated machine, execute SETUP_CONSTANTS and evaluate B expressions, e.g. in the B-Console of ProB2-UI. The following expressions refer to the order.xml example above (expression, followed by its value):
/* all elements with a given name */card({e | e : ran(XML_DATA) & e'Element = "item"}) = 2
/* the names of all customers: unwrap the typed attribute values with the inverse constructor */{n | #e.(e : ran(XML_DATA) & e'Element = "customer" & n = XmlString~(e'attributes("name")))} = {"Müller","Paul"}
/* direct children of the element with recId 2: the last entry of pIds is the parent */{i | #c.(c : ran(XML_DATA) & last(c'pIds) = 2 & i = c'recId)} = {3}
/* all descendants of the element with recId 4, using maxCId */{i | #c.(c : ran(XML_DATA) & c'recId > 4 & c'recId <= (XML_DATA(4))'maxCId & i = c'recId)} = {5}The parent of an element e (other than the root) is XML_DATA(last(e'pIds)), because recId is the index in XML_DATA.
Using the data from other machines
Section titled “Using the data from other machines”Rules and checks should not be added to the generated machine, because it is overwritten by the next import. Put them into a separate machine that SEES the data machine instead (or into a rules machine):
MACHINE OrderChecksSEES orderDEFINITIONS elements(name) == {e | e : ran(XML_DATA) & e'Element = name}; children(p) == {c | c : ran(XML_DATA) & last(c'pIds) = p'recId}ASSERTIONS /* every customer has at least one item */ !c.(c : elements("customer") => #i.(i : children(c) & i'Element = "item"))ENDIf the XML file changes, re-import it with Update only Translated Data ticked (same machine name and output location) and reload the machine; OrderChecks is not touched.
Command line
Section titled “Command line”XML2B can also be used without ProB2-UI, either as a command line tool or from Java via the class XML2B (translate() returns the B AST). A standalone jar is built with ./gradlew shadowJar. The first argument is the XML file; the options correspond to the options of the dialog:
java -jar XML2B.jar order.xml -xsd order.xsd -frw SICSTUS -o order.mch| Option | Meaning |
|---|---|
-xsd FILE |
use the XSD file for validation and type extraction |
-frw SICSTUS|SWI|NONE |
Prolog system for the fast read/write format; NONE writes plain Prolog text (the dialog offers SICSTUS and NONE) |
-o FILE |
output machine; the name of the machine and the directory are taken from this path |
-update |
update only the .probdata file |
-version |
print the version of XML2B |
XML (untyped)
Section titled “XML (untyped)”The entry XML (untyped) does not translate the file at import time. The generated machine calls the external function READ_XML of LibraryXML.def (see External Functions), which reads the file each time the constants are set up and converts it to a B data structure of records. In contrast to XML2B there is no type derivation, which is the main reason to prefer XML2B for data validation.
The only option is the Encoding of the file: auto (default), ISO-8859-1, ISO-8859-2, ISO-8859-15, UTF-8, UTF-16, UTF-16LE, UTF-16BE, UTF-32, UTF-32LE, UTF-32BE, ANSI_X3.4-1968 and windows 1252.
Generated machine for /home/user/data/order.xml:
MACHINE orderDEFINITIONS "LibraryXML.def"CONSTANTS XML_DATAPROPERTIES XML_DATA = READ_XML("/home/user/data/order.xml","auto")ENDNote that LibraryXML.def can also convert JSON files into the same data structure (READ_JSON_AS_XML and READ_JSON_FROM_STRING_AS_XML).
The entry JSON has no additional options. The generated machine reads the file with the external function READ_JSON of the library LibraryJSON (see External Functions). Both the machine LibraryJSON.mch (for the free type) and the definition file LibraryJSON.def are needed, and the generated machine includes both.
Generated machine for /home/user/data/stations.json:
MACHINE stations SEES LibraryJSONDEFINITIONS "LibraryJSON.def"CONSTANTS JSON_DATAPROPERTIES JSON_DATA = READ_JSON("/home/user/data/stations.json")ENDThe data model
Section titled “The data model”The value of JSON_DATA is of the free type JsonValue:
FREETYPES JsonValue = JsonNull, JsonBoolean(BOOL), JsonNumber(FLOAT), JsonString(STRING), JsonArray(seq(JsonValue)), JsonObject(STRING +-> JsonValue)| JSON | B value |
|---|---|
| object | JsonObject(f) where f is a partial function from the keys to JsonValues |
| array | JsonArray(s) where s is a sequence of JsonValues |
| string | JsonString(str) |
| number | JsonNumber(x) with a floating point number x; this includes integers (3 becomes 3.0) |
true, false |
JsonBoolean(TRUE), JsonBoolean(FALSE) |
null |
JsonNull |
Example
Section titled “Example”Input file stations.json:
{ "network": "Demo", "stations": [ { "id": "A", "name": "Alpha", "platforms": 3, "terminal": true }, { "id": "B", "name": "Beta", "platforms": 2, "terminal": false } ], "updated": null}After SETUP_CONSTANTS, JSON_DATA has the following value (reformatted):
JsonObject({ "network" |-> JsonString("Demo"), "stations" |-> JsonArray([ JsonObject({"id"|->JsonString("A"), "name"|->JsonString("Alpha"), "platforms"|->JsonNumber(3.0), "terminal"|->JsonBoolean(TRUE)}), JsonObject({"id"|->JsonString("B"), "name"|->JsonString("Beta"), "platforms"|->JsonNumber(2.0), "terminal"|->JsonBoolean(FALSE)}) ]), "updated" |-> JsonNull })Use the inverse constructors (see Free Types) to navigate into the structure:
/* the keys of the top-level object */dom(JsonObject~(JSON_DATA)) = {"network","stations","updated"}
/* the list of stations as a sequence of JsonValues */size(JsonArray~(JsonObject~(JSON_DATA)("stations"))) = 2
/* the names of all stations */{n | #s.(s : ran(JsonArray~(JsonObject~(JSON_DATA)("stations"))) & n = JsonString~(JsonObject~(s)("name")))} = {"Alpha","Beta"}
/* the ids of all stations with three platforms: compare with the wrapped value */{i | #s.(s : ran(JsonArray~(JsonObject~(JSON_DATA)("stations"))) & JsonObject~(s)("platforms") = JsonNumber(3.0) & i = JsonString~(JsonObject~(s)("id")))} = {"A"}Wrapping the navigation into DEFINITIONS keeps checks readable. As for XML, put them into a separate machine:
MACHINE StationChecksSEES LibraryJSON, stationsDEFINITIONS obj(v) == JsonObject~(v); arr(v) == JsonArray~(v); station_list == arr(obj(JSON_DATA)("stations"))ASSERTIONS /* every station has the keys id, name and platforms */ !s.(s : ran(station_list) => {"id","name","platforms"} <: dom(obj(s)))ENDApplying obj(s)("name") to an object without the key "name" is not well-defined; test with "name" : dom(obj(s)) if keys are optional.
The entry CSV reads the file with READ_CSV or READ_CSV_SEQUENCE of LibraryCSV.def.
Import as a B Sequence of Rows (Set otherwise)
(ticked by default) The file becomes a sequence of rows (READ_CSV_SEQUENCE, type seq(...)), so the order of the rows is preserved and the rows can be addressed by their index. Otherwise the rows form a set (READ_CSV, type POW(...)).
Skip First Row
Ignore the first row, e.g. a header line.
Allow Additional Columns
Controls whether rows with additional columns are accepted. It is switched on automatically if the rows of the file have different lengths.
Number of columns
The number of columns of the generated type. It is preset to the largest number of columns found in the file.
Example file trains.csv:
id,name,seatsT1,Express,120T2,Local,80Generated machine with the default options (the file name is shortened):
MACHINE trainsDEFINITIONS "LibraryCSV.def"CONSTANTS CSV_DATAPROPERTIES CSV_DATA : seq(STRING*STRING*STRING) & // specify custom column types CSV_DATA = READ_CSV_SEQUENCE("/home/user/data/trains.csv",FALSE,TRUE)ENDThe three arguments of READ_CSV_SEQUENCE are the file, Skip First Row and Allow Additional Columns. All columns are typed as STRING by default, so CSV_DATA contains the header line as well:
CSV_DATA = [("id"|->"name"|->"seats"),("T1"|->"Express"|->"120"),("T2"|->"Local"|->"80")]The typing predicate in the generated machine is the place to refine the column types (for instance seq(STRING*STRING*INTEGER) together with Skip First Row for a numeric column); see the documentation of LibraryCSV.def in External Functions. Because the generated machine is overwritten by a new import, make such edits in a copy of the machine or re-apply them after re-importing.
railML 3
Section titled “railML 3”railML 3 files are imported by a dedicated, certified interface called railML2B. It is available as railML 3 in the Data Import menu, and railML files (.railml, .railmlx) can also be opened directly. The railML import has its own options dialog and offers validation, visualisation and animation of the railway data. See the article ProB for railML for details.
See also
Section titled “See also”- ProB2-UI
- ProB for railML
- Free Types
- Rules-DSL (validation of imported data)
- External Functions (libraries for XML, JSON and CSV)
- JSON and Sockets
- XML2B on GitHub
- Type-Safe Validation of XML Railway Data in B (paper using XML2B)