path to element with conditions on parent (s) attributes using xpath, lxml, python

advertisements

I am working on project using lxml. here is a sample xml

<PatientsTree>
  <Patient PatientID="SKU065427">
    <Study StudyInstanceUID="25.2.9.2.1107.5.1.4.49339.30000006050107501192100000001">
      <Series SeriesInstanceUID="2.16.840.1.113669.1919.1176798690"/>
      <Series SeriesInstanceUID="2.16.840.1.113669.1919.1177084041"/>
      <Series SeriesInstanceUID="25.2.9.2.1107.5.1.4.49339.30000006050108064034300000000"/>
    </Study>
  </Patient>
  <Patient PatientID="SKU55527">
    <Study StudyInstanceUID="25.2.9.2.1107.5.1.4.49339.30000006120407393721800000007">
      <Series SeriesInstanceUID="2.16.840.1.113669.1919.1198835144"/>
    </Study>
    <Study StudyInstanceUID="25.2.9.2.1107.5.1.4.49339.30000007010207164403100000013">
      <Series SeriesInstanceUID="2.16.840.1.113669.1919.1198835358"/>
  </Patient>
</PatientsTree>

Suppose I want to get to the series element with conditions

  1. PatientID="SKU55527"
  2. StudyInstanceUID="25.2.9.2.1107.5.1.4.49339.30000007010207164403100000013";

My result will be :

<Series SeriesInstanceUID="2.16.840.1.113669.1919.1198835358"/>

If I can understand this solution then I will move one step closer in learning xml. P.S I am working with python and lxml and xpath


import lxml.etree as le
with open('data.xml') as f:
    doc=le.parse( f )
patientID="SKU55527"
studyInstanceUID="25.2.9.2.1107.5.1.4.49339.30000007010207164403100000013"
xpath='''\
    /PatientsTree
        /Patient[@PatientID="{p}"]
            /Study[@StudyInstanceUID="{s}"]
                /Series'''.format(p=patientID,s=studyInstanceUID)
seriesInstanceUID=doc.xpath(xpath)
for node in seriesInstanceUID:
    print(node.attrib)
    # {'SeriesInstanceUID': '2.16.840.1.113669.1919.1198835358'}