Borrar filtros
Borrar filtros

writestruct() fails to write empty child element to XML file

1 visualización (últimos 30 días)
Matt
Matt el 12 de Jun. de 2024
Comentada: Voss el 12 de Jun. de 2024
I need to write a empty, nested element within an XML file. An XML example of what I'd like to achieve is:
<?xml version="1.0" encoding="UTF-8"?>
<Problem>
<elementA>14</elementA>
<elementB>
<child/>
</elementB>
</Problem>
The nested element in this case is called "child". I expected the following MATLAB code to produce this result:
s.elementA = 14;
s.elementB.child = [];
writestruct(s,'test.xml','StructNodeName','Problem')
However, this generates the following XML, whereupon the "child" element is entirely missing:
<?xml version="1.0" encoding="UTF-8"?>
<Problem>
<elementA>14</elementA>
<elementB/>
</Problem>
How can I produce a result with an empty, nested element?

Respuesta aceptada

Voss
Voss el 12 de Jun. de 2024
s.elementA = 14;
s.elementB.child = struct();
writestruct(s,'test.xml','StructNodeName','Problem')
type('test.xml')
<?xml version="1.0" encoding="UTF-8"?> <Problem> <elementA>14</elementA> <elementB> <child/> </elementB> </Problem>
  2 comentarios
Matt
Matt el 12 de Jun. de 2024
Thank you, this is cleaner than the other solution I posted.

Iniciar sesión para comentar.

Más respuestas (1)

Matt
Matt el 12 de Jun. de 2024
Well, not even 15 minutes and I found the solution myself. I find it strange that the following must be done to achieve a nested, empty element of an XML, but here is the approach:
s.elementA = 14;
s.elementB.child.dummy = [];
writestruct(s,'test.xml','StructNodeName','Problem')
Including the dummy field informs MATLAB that child is a struct (and not an empty double, as specified in my question). That child is now explictly a struct causes the creation of an empty "child" element in the XML.
<?xml version="1.0" encoding="UTF-8"?>
<Problem>
<elementA>14</elementA>
<elementB>
<child/>
</elementB>
</Problem>
I hope someone else finds this answer useful.

Productos


Versión

R2020b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by