writestruct

Writes a structure to an XML or JSON file.

Category: Data Import and Analysis > Data Import and Export

Syntax

writestruct(S, filename)

Writes S; the format follows the extension (.xml or .json).

Description

Each field becomes an element: a scalar or text becomes a leaf, and a nested struct becomes a nested element. In XML, a numeric vector is written as repeated elements with the field name, and the root element is called struct. In JSON the structure maps to an object and vectors map to arrays.

readstruct reads the file back into a structure, so the pair is a convenient way to store configuration or results in a readable form.

Input arguments

S
Structure or struct array with numeric, text or nested struct fields.
filename
Output file name ending in .xml or .json.

Example

Struct to XML

s.name = 'run1';
s.n = [1 2 3];
s.opts.tol = 0.5;
writestruct(s, 'struct_demo.xml');
type struct_demo.xml
Output

<?xml version="1.0" encoding="UTF-8"?>
<struct>
    <name>run1</name>
    <n>1</n>
    <n>2</n>
    <n>3</n>
    <opts>
        <tol>0.5</tol>
    </opts>
</struct>

Notes

In JSON output MatLivre writes numbers with a decimal point (3.0 for 3).

See also

readstruct jsonencode struct writecell