Create a nested XML file
Afficher commentaires plus anciens
I would like to create an XML file where elements can be nested inside each other. I haven't found much documentation of this and I have got this working without nesting but when I try to next elements inside of each other I don't get my expected output. Take the following example (taken from Mathworks website):
docNode = com.mathworks.xml.XMLUtils.createDocument('root_element');
docRootNode = docNode.getDocumentElement;
docRootNode.setAttribute('attr_name','attr_value');
for i=1:5
thisElement = docNode.createElement('child_node');
thisElement.appendChild(docNode.createTextNode(sprintf('%i',i)));
docRootNode.appendChild(thisElement);
end
docNode.appendChild(docNode.createComment('this is a comment'));
xmlFileName = ['tempname.xml'];
xmlwrite(xmlFileName,docNode);
type(xmlFileName);
This give the output (as I would expect):
<?xml version="1.0" encoding="utf-8"?>
<root_element attr_name="attr_value">
1
2
3
4
5
</root_element><!--this is a comment-->
But when I try to add another node into the picture:
docNode = com.mathworks.xml.XMLUtils.createDocument('root_element');
docRootNode = docNode.getDocumentElement;
docRootNode.setAttribute('attr_name','attr_value');
for i=1:5
thisElement = docNode.createElement('child_node');
thisElement.appendChild(docNode.createTextNode(sprintf('%i',i)));
docRootNode.appendChild(thisElement);
nestedElement = docNode.createElement('nested_node');
nestedElement.appendChild(docNode.createTextNode(sprintf('%i',i + 10)));
thisElement.appendChild(nestedElement);
end
docNode.appendChild(docNode.createComment('this is a comment'));
xmlFileName = ['tempname.xml'];
xmlwrite(xmlFileName,docNode);
type(xmlFileName);
I get this output:
<?xml version="1.0" encoding="utf-8"?>
<root_element attr_name="attr_value">
1<nested_node>11</nested_node>
2<nested_node>12</nested_node>
3<nested_node>13</nested_node>
4<nested_node>14</nested_node>
5<nested_node>15</nested_node>
</root_element><!--this is a comment-->
But this is the input I was expecting:
<?xml version="1.0" encoding="utf-8"?>
<root_element attr_name="attr_value">
1
<nested_node>11</nested_node>
2
<nested_node>12</nested_node>
3
<nested_node>13</nested_node>
4
<nested_node>14</nested_node>
5
<nested_node>15</nested_node>
</root_element><!--this is a comment-->
Is there any way that you can add in the newlines from the code?
Réponses (0)
Catégories
En savoir plus sur Structured Data and XML Documents dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!