Add newlines into an XML file
7 views (last 30 days)
Show older comments
Is there any way to pragmatically add in newline characters into an XML file? Lets say I have something like this:
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:
<?xml version="1.0" encoding="utf-8"?>
<root_element attr_name="attr_value">
<child_node>1</child_node>
<child_node>2</child_node>
<child_node>3</child_node>
<child_node>4</child_node>
<child_node>5</child_node>
</root_element><!--this is a comment-->
But I would like it to look like:
<?xml version="1.0" encoding="utf-8"?>
<root_element attr_name="attr_value">
<child_node>1</child_node>
<child_node>2</child_node>
<child_node>3</child_node>
<child_node>4</child_node>
<child_node>5</child_node>
</root_element><!--this is a comment-->
So is there any way that I can use docRootNode to add in newlines into the xml?
0 Comments
Answers (1)
Nick
on 28 Nov 2022
I think the answer is obvious, just add
docNode.appendChild(docNode.createTextNode(newline));
after creation of each "child_node".
Unfortunately, it doesn't add pretty formatting (if you need to indent following nodes, you'd need to add some spaces yourself in this text node.
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!