Andrea Fresa
Andrea Fresa

Reputation: 341

Can't retrieve elements with xpath from an OpcUa Nodeset

I am trying to query with xpath this XML file (https://github.com/OPCFoundation/UA-Nodeset/blob/master/Robotics/Opc.Ua.Robotics.NodeSet2.xml). I am trying to get all the elements inside the tag "UANodeSet" but I always get an empty return. I am working with node js Here it is my code:

nodes = fs.readFileSync(Nodeset+".xml", "utf-8");
var data = xpath.select("//UANodeSet", nodes)
fs.writeFileSync("./data.xml" , data);

The library that I am using comes from npm and it is called xpath.

The expectation is having all the child elements inside UANodeSet, reality is that I am having an empty return. Do you know how to solve it?

Sorry, first time working with xpath.

Ok, first problem is done. Now I am trying to retrieve all the UAObjectType, but it seems like the xml output is really wrong foermatted and I don´t know why. Here it is the code:

var select = xpath.useNamespaces({"ns" : "http://www.w3.org/2001/XMLSchema-instance" , "ns1" : "http://opcfoundation.org/UA/2011/03/UANodeSet.xsd" , "ns2" : "http://opcfoundation.org/UA/2008/02/Types.xsd", "ns3" : "http://www.siemens.com/OPCUA/2017/SimaticNodeSetExtensions" ,"ns4" : "http://www.w3.org/2001/XMLSchema" });
var data = select('//ns1:UAObjectType' , ns)
fs.writeFileSync("./data.xml" , data);

Does anyone knows how to solve it?

Upvotes: 1

Views: 153

Answers (1)

Jack Fleeting
Jack Fleeting

Reputation: 24930

The xml file uses namespaces and that seems to trip up the xpath expression. Try something like this and see if it work:

dom = require('xmldom').DOMParser
var doc = new dom().parseFromString(nodes)
var targets = xpath.select("//*[local-name()='UAObject']", doc)

The other solution is:

var select = xpath.useNamespaces({"ns1" : "http://opcfoundation.org/UA/2011/03/UANodeSet.xsd" });
var data = select('//ns1:UAObjectType' , ns)

Upvotes: 1

Related Questions