XPath query with default namespace in XML file
22 views (last 30 days)
Show older comments
Matlab introduced a MATLAB API for XML Processing (I believe in 2021a).
I am using this API with XPath expressions to extract data from XML files. However, this fails when the XML file has a default namespace registered.
For example with this XML file test.xml:
<books xmlns="http://www.contoso.com/books" xmlns:i="http://www.contoso.com/currency">
<book>
<title>Title</title>
<author>Author Name</author>
<i:price>5.50</i:price>
</book>
</books>
Using the following snippet:
import matlab.io.xml.dom.*
import matlab.io.xml.xpath.*
xmlFilePath = "path\to\test.xml";
xmlDom = parseFile(Parser, xmlFilePath);
xpathPrice = "//i:price";
xpathAuthor = "//author";
res = evaluate(Evaluator, xpathPrice, xmlDom)
works for xpathPrice but fails for xpathAuthor (in the sense that it returns an empty result instead of the author node from the example).
Browsing through the different options, I could not come up with a solution. I am working on Matlab 2021b.
I know that I could use getElementsByTagName but I do require the functionality provided by XPath to identify nodes.
Are there any hints on how I could get that working?
Thanks!
0 Comments
Accepted Answer
Sakshay
on 29 Nov 2022
Hello Chris,
As per my understanding, you are trying to access elements of an XML file, using XPath. But it seems that the elements with a default namespace having no prefix are not being captured.
This problem here seems to be with how XPath works, rather than in the MATLAB API.
Elements without a prefix, can be accessed using the "local-name()" attribute. As an example, for your case, the query would look like:
xPathAuthor = '//*[local-name()="book"]';
res = evaluate(Evaluator, xPathAuthor, xmlDom);
For information, on the XPath Evaluator Package, you can refer to the following documentation:
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!