How can I add XML attributes and corresponding values in line to RootNode
Show older comments
Hello,
I am trying to create an XML document using the following code:
docNode = com.mathworks.xml.XMLUtils.createDocument...
('Part')
docRootNode = docNode.getDocumentElement;
docRootNode.setAttribute('Name','Piston');
ChildNode_Names={'PartType', 'PartInventorySerialNumber', 'PartCreateDate',...
'PartReport', 'PartActive'};
ChildNode_Values={'Ring', '23', '11/20/2015', '1', '1'};
for i=1:5
thisElement = docNode.createElement(ChildNode_Names(i));
thisElement.appendChild...
(docNode.createTextNode(sprintf('%s',ChildNode_Values{i})));
docRootNode.appendChild(thisElement);
end
xmlFileName = ['Part.xml'];
xmlwrite(xmlFileName,docNode);
type(xmlFileName);
This is the XML document which I create:

I am trying to add attributes and corresponding values directly under (in-line with) the text node elements.
I can't seem to be able to add an attribute unless I add it as a child to one of the text node elements, such as below:

Done using this code:
docNode = com.mathworks.xml.XMLUtils.createDocument...
('Part')
docRootNode = docNode.getDocumentElement;
docRootNode.setAttribute('Name','Piston');
ChildNode_Names={'PartType', 'PartInventorySerialNumber', 'PartCreateDate',...
'PartReport', 'PartActive'};
ChildNode_Values={'Ring', '23', '11/20/2015', '1', '1'};
for i=1:5
thisElement = docNode.createElement(ChildNode_Names(i));
thisElement.appendChild...
(docNode.createTextNode(sprintf('%s',ChildNode_Values{i})));
docRootNode.appendChild(thisElement);
end
entry_node = docNode.createElement('Entry');
docNode.getDocumentElement.appendChild(entry_node);
address_node = docNode.createElement('Address');
address_node.setTextContent('3 Apple Hill Dr, Natick MA')
% set an attribute directly
address_node.setAttribute('type','work');
entry_node.appendChild(address_node);
% or create the attribute as a node
has_zip_attribute = docNode.createAttribute('hasZip');
has_zip_attribute.setNodeValue('no');
address_node.setAttributeNode(has_zip_attribute);
xmlFileName = ['Part.xml'];
xmlwrite(xmlFileName,docNode);
type(xmlFileName);
This is not what I am looking for though.
I need my attributes and the corresponding values on the same line, and directly inline with the PartType node, like in the image below (sorry for having to cover up the variables):

Can someone please help me?
Accepted Answer
More Answers (1)
ANKAN BHATTACHARYYA
on 20 Nov 2016
0 votes
if i have <stroke stroke_no="2" / > then how can i do : <stroke stroke_no="2" stroke_name="XYZ" / > ?
Categories
Find more on Structured Data and XML Documents in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!