1

I have an xml document in cim/xml format. The document comprises two namespaces

  • rdf,
  • cim.

A part of the document is shown below:

<?xml version='1.0' encoding='UTF-8'?>
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:cim="http://iec.ch/TC57/2013/CIM-schema-cim16#">
  <cim:Terminal rdf:ID="_08d0270e-f753-4812-a1cc-0550d9864a23">
    <cim:IdentifiedObject.name>C:Y8CHTT402:ETTR:1</cim:IdentifiedObject.name>
    <cim:Terminal.ConductingEquipment rdf:resource="#_93030a09-6aac-46b5-bf5b-f75b90841675"/>
    <cim:ACDCTerminal.sequenceNumber>1</cim:ACDCTerminal.sequenceNumber>
  </cim:Terminal>
  <cim:Terminal rdf:ID="_5451fc7e-5d94-4d30-ab58-744ab841334d">
    <cim:IdentifiedObject.name>C:Y8CHTT402:ETTR:2</cim:IdentifiedObject.name>
    <cim:Terminal.ConductingEquipment rdf:resource="#_93030a09-6aac-46b5-bf5b-f75b90841675"/>
    <cim:ACDCTerminal.sequenceNumber>2</cim:ACDCTerminal.sequenceNumber>
  </cim:Terminal>
</rdf:RDF>

My goal is to find a Terminal etree object with a given rdf:ID.

I'm able to find all elements of a given type using etree.xpath. I have found a way to it using the lxml documentation.

from lxml import etree
root = etree.parse(my_file)
RDFNS = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"
CIMNS = "http://iec.ch/TC57/2013/CIM-schema-cim16#"

all_objts = root.xpath('/y:RDF/x:Terminal' % nodeID,
                       namespaces={'x': CIMNS, 'y': RDFNS})  # This returns a list of all terminal objects

But I fail to obtain only one element with a given rdf:ID:

nodeID = "_08d0270e-f753-4812-a1cc-0550d9864a23"
tar_obj = root.xpath('/y:RDF/x:Terminal[@ID="%s"]' % nodeID,
                     namespaces={'x': CIMNS, 'y': RDFNS})  # Returns an empty list

I have found a very similar post but it doesn't answer this question properly.

I'd like to add the namespace prefix to the ID tag (as shown below)

root.xpath('/y:RDF/x:PowerTransformer[y:@ID="%s"]' % nodeID,
           namespaces={'x': CIMNS, 'y': RDFNS})

, but that doesn't work

File "lxml.etree.pyx", line 1507, in lxml.etree._Element.xpath (src\lxml\lxml.etree.c:52198)

  File "xpath.pxi", line 307, in lxml.etree.XPathElementEvaluator.__call__ (src\lxml\lxml.etree.c:152124)

  File "xpath.pxi", line 227, in lxml.etree._XPathEvaluatorBase._handle_result (src\lxml\lxml.etree.c:151097)

  File "xpath.pxi", line 213, in lxml.etree._XPathEvaluatorBase._raise_eval_error (src\lxml\lxml.etree.c:150950)

XPathEvalError: Invalid expression

Is there a way to search for an object with a given rdf:ID using etree.xpath in a document with multiple namespaces?

Premysl Vorac
  • 473
  • 6
  • 16

1 Answers1

1

There is an error in the predicate in this expression:

root.xpath('/y:RDF/x:PowerTransformer[y:@ID="%s"]' % nodeID,
           namespaces={'x': CIMNS, 'y': RDFNS})

You need to change [y:@ID="%s"] to [@y:ID="%s"].

mzjn
  • 48,958
  • 13
  • 128
  • 248