Clear Filters
Clear Filters

How to align xml file?

5 views (last 30 days)
Mark Golberg
Mark Golberg on 25 Jan 2022
Answered: Shimon Elkin on 14 Feb 2022
Hey,
I'm using
import matlab.io.xml.dom.*
doc_A = parseFile(Parser , file_A_fullPath);
doc_B = parseFile(Parser , file_B_fullPath);
to copy a Node from file_A to file_B.
I'm doing this by:
  1. find an existing Node in B, and remove it.
  2. import Node from A to B.
  3. append Node to B
besically it's working, BUT:
1) after removing the Node from B, I got an empty line. Can this be removed? (I know that xml doesn't care about, just for visual clarity)
2) after appending Node to B, the Node is "not properly closed", so when running it multiple time, I get a visual mixup. please see attached pics.
can this be aligned somehow? I mean, basically I'd like to do somesort of "\n" (finish line) after each appendChild action. (ModuleType)
Also,
can someone explain please the difference between readxml function and the above method?
DOMnode = xmlread(xmlfile);
docRootNode = getDocumentElement(DOMnode);
how can I use importChild , appendChild , removeChild with DOMnode and/or docRootNode?

Answers (1)

Shimon Elkin
Shimon Elkin on 14 Feb 2022
you can find the answer to the white space question, this is a limitation of the Saxon XML processor at the link, https://www.mathworks.com/matlabcentral/answers/94189-why-does-xmlread-introduce-extra-whitespace-into-my-xml-file [mathworks.com].
as for the second question you can use the script below:
import matlab.io.xml.dom.*
import matlab.io.xml.xpath.*
docA = parseFile(Parser,'a.xml');
stripEmptyTextNodes(docA);
config = evaluate(Evaluator,'/Configuration',docA);
modType = evaluate(Evaluator,'ModuleType',config);
removeChild(config,modType);
writer = DOMWriter;
writer.Configuration.FormatPrettyPrint = true;
writeToFile(writer,docA,'a1.xml');
function stripEmptyTextNodes(node)
import matlab.io.xml.dom.*
nodelist = getChildNodes(node);
i = 0;
while i < getLength(nodelist)
child = item(nodelist,i);
if getNodeType(child) == node.TEXT_NODE
if isempty(strtrim(getTextContent(child)))
child.getParentNode().removeChild(child);
i = i-1;
end
end
i = i+1;
stripEmptyTextNodes(child);
end
end

Products

Community Treasure Hunt

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

Start Hunting!