Add newlines into an XML file

5 ビュー (過去 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 Center および File ExchangeStructured 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