Add newlines into an XML file

16 次查看(过去 30 天)
Duke
Duke 2013-10-24
回答: Nick 2022-11-28
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?

回答(1 个)

Nick
Nick 2022-11-28
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.

类别

Help CenterFile Exchange 中查找有关 Structured Data and XML Documents 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by