0

I am really struggeling finding the parent of an element I have searched for using this code, I am searching for "NOTE2"="CU008" in the parent which has the DESCR="RmTmp"

def SetAttribute(tag, rom):
    for elm in root.findall(f".//OI[@DESCR='{tag}']/PI[@Name='NOTE2']"):
        if elm.attrib == {'Name': 'NOTE2', 'Value': f'{rom}'}:
            print("success")

SetAttribute("RmTmp", "CU008")

The XML file is extremely large, so I cannot post all of it, but here is a sample of it:

        <OI DESCR="RmTmp" NAME="Romtemperatur" TYPE="trend.ETLog">
          <PI Name="ForceReadTimeout" Value="60000"/>
          <PI Name="LastTransferredTimestamp" Value="Tx05eb76f79f16e0f1"/>
          <PI Name="LogArray" Unit="0x280001"/>
          <PI Name="MeterEndTime" Value="Tx05e905db0039e8f1"/>
          <PI Name="MeterStartTime" Value="Tx05e905db0039e8f1"/>
          <PI Name="MeterTime" Value="Tx05e905db003da9f1"/>
          <PI Name="MonitoredLog">
            <Reference DeltaFilter="0" Object="../../Trendlogger/RmTmp_Tlog" Retransmit="0" TransferRate="10"/>
          </PI>
          <PI Name="NOTE1" Value="RmTmp"/>
          <PI Name="NOTE2" Value="CU008"/>
          <PI Name="Threshold" Value="10"/>
        </OI>

What I am trying to change is in the first OI: "DESCR="RmTmp" to something else, which I will get from a .csv file.

But the thing is, if I search for "DESCR="RmTmp"" I will find 4 elements, but if I search like I did above I find the correct one, but I dont know how to change the DESCR in the parent of my search.

if I use this code to search for element attributes:

def SetAttribute(tag):
  for elm in root.findall(f".//OI[@DESCR='{tag}']/PI[@Name='NOTE2']"):
    print(elm.attrib)

SetAttribute("RmTmp")

I get this output: Output child

and if I search for these attributes using this code:

def SetAttribut(tag):
  for elm in root.findall(f".//OI[@DESCR='{tag}']"):
    print(elm.attrib)

SetAttribut("RmTmp")

I get this output: output parent

1 Answers1

0

In XPath, you can find the parent element of an element by navigating up the parent axis one step. Simply append /parent::* to the end of your existing XPath.

https://www.w3.org/TR/1999/REC-xpath-19991116/#axes

.//OI[@DESCR='{tag}']/PI[@Name='NOTE2']/parent::OI

But if I understand your question correctly, then more simply you can search for the parent OI element directly and use a predicate to check that it has a child element with the desired characteristics.

.//OI[@DESCR='{tag}'][PI/@Name='NOTE2']
Conal Tuohy
  • 2,561
  • 1
  • 8
  • 15