'How to select the ancestors of an xml node using xpath in matlab
I have a xml file and want to select the ancestors name of each leaf node using the Xpath in matlab, I have tried to do it by every time I get 0 ancestors.
<?xml version="1.0" encoding="UTF-8"?>
<taxonomy>
<concept name="con1">
<concept name="con11">
<concept name="con1033990258">
<concept name="con271874239">
<concept name="con1657241849">
<concept name="con1448945150">
<instance name="inst686829093"/>
<instance name="inst1379512917"/>
<instance name="inst2072196703"/>
</concept>
</concept>
</concept>
</concept>
<concept name="con12">
<instance name="inst2072192589"/>
</concept>
<concept name="con13"></concept>
<concept name="con14"></concept>
</concept>
</taxonomy>
And this is how I tried, I first stored all the instances name in in the instance_matrix which is a string matrix. Then for each instance, I looked for it ancestors but every time I get 0 and it's not right. As example the number of ancestors of the Instance ="inst686829093" would be 6 but me I get 0.
Instances = xDoc.getElementsByTagName('instance');
InstanceName = char(Instances.item(0).getAttribute('name'));
instance_matrix = strings(Instances.getLength,1);
IncestorList =strings(Instances.getLength,100);
for i= 0:Instances.getLength-1
instance_matrix(i+1)=string(Instances.item(i).getAttribute('name'));
end
for i= 0:Instances.getLength-1
expression = xpath.compile('//ancestor-or-self::instance[@name="' + instance_matrix(i+1) + '"]');
Incestor = expression.evaluate(xDoc, XPathConstants.NODESET);
for j = 0:Incestor.getLength-1
IncestorList(i+1,j+1) = char(Incestor.item(j).getAttribute('name'));
end
end
If anyone could help me, I would be very grateful thank you.
Solution 1:[1]
Getting @name attributes of all ancestors of inst686829093 with lxmland xpath
>>> from lxml import etree
>>> tree = etree.parse('test.xml')
>>> anc = tree.xpath('//instance[@name="inst686829093"]/ancestor::*/@name')
>>> anc
['con1', 'con11', 'con1033990258', 'con271874239', 'con1657241849', 'con1448945150']
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | LMC |
