Add newlines into an XML file
조회 수: 5 (최근 30일)
이전 댓글 표시
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
답변 (1개)
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.
댓글 수: 0
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!