How can I create easily readable XML files with clear indentation and newlines?

13 Ansichten (letzte 30 Tage)
I am executing a MATLAB script which creates an XML file using 'xmlwrite'. I noticed that the outputted file is more compact in format. Is there any way to generate a more human-readable XML file?

Akzeptierte Antwort

MathWorks Support Team
MathWorks Support Team am 25 Okt. 2021
The XML file can be made more readable, rather than compact, in a couple of ways depending on your workflow. You may be using either the MATLAB API for XML Processing (MAXP) or the Java API for XML Processing (JAXP), both of which are discussed in the following documentation page:
Let us look at the workflows used to create more readable XML files for both of these API's:
1) MAXP ("matlab.io.xml.dom.Document" and "matlab.io.xml.dom"): Run the following code to create a DOM document:
import matlab.io.xml.dom.*
docNode = Document('DocumentName');
After adding the file content, set the "writer" object's "FormatPrettyPrint" option to "true", then write the file:
writer = matlab.io.xml.dom.DOMWriter;
writer.Configuration.FormatPrettyPrint = true;
writeToFile(writer,docNode,'filename');
Note that the 'filename' should be replaced by the name of your file.
2) JAXP ("com.mathworks.xml.XMLUtils.createDocument" and "xmlwrite"): Run the following code to create a DOM document:
docNode = com.mathworks.xml.XMLUtils.createDocument('DocumentName');
docRootNode = docNode.getDocumentElement;
After adding the file content, set the "INDENT" property to "yes" using Java objects:
% Create transformer, set "INDENT" to "yes"
import javax.xml.transform.*
import javax.xml.transform.dom.*
import javax.xml.transform.stream.*
tfactory = TransformerFactory.newInstance;
transformer = tfactory.newTransformer;
src = DOMSource(docNode);
stream = java.io.StringWriter;
dst = StreamResult(stream);
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.transform(src, dst);
result = char(stream.toString);
% Save file
fid = fopen('filename','Wt');
fwrite(fid,result);
fclose(fid);
Again, note that the 'filename' should be replaced by the name of your file. More information on the Java part of this workflow can be found below:

Weitere Antworten (0)

Produkte


Version

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by