0

folks! I'm trying to parse some weird formed XML:

<?xml version="1.0" encoding="UTF-8"?>
<analytics>
  <standard1>
    ...
    <attributes>
      <attribute name="agentname" value="userx userx" />
      <attribute name="agentpk" value="5" />
      <attribute name="analytics:callid" value="757004000003597" />
      ...
      <attribute name="wrapuptime" value="0" />
    </attributes>
  </standard1>
  <standard2>
    ...
    <attributes>
      <attribute name="agentname" value="userx userx" />
      <attribute name="agentpk" value="5" />
      <attribute name="analytics:callid" value="757004000003597" />
      ...
      <attribute name="wrapuptime" value="0" />
    </attributes>
  </standard2>
  <engines>
  ...
  </engines>
</analytics>

Since both name and value are attributes, I have no idea how to access value by name without looping through the whole attributes subsection with a foreach cycle.

Any ideas how to get a direct access using ElementTree?

1 Answer 1

1

You can use a simple XPath expression to filter attribute element by the value of name attribute. Sample working code:

import xml.etree.ElementTree as ET

data = """<?xml version="1.0" encoding="UTF-8"?>
<analytics>
  <standard>
      <attributes>
        <attribute name="agentname" value="userx userx" />
        <attribute name="agentpk" value="5" />
        <attribute name="analytics:callid" value="757004000003597" />
        <attribute name="wrapuptime" value="0" />
      </attributes>
  </standard>
</analytics>
"""

root = ET.fromstring(data)
print(root.find(".//attribute[@name='agentname']").attrib["value"])

Prints:

userx userx

Beware that xml.etree.ElementTree has a limited XPath support.

Sign up to request clarification or add additional context in comments.

4 Comments

@e-pirate well, I am still not sure what exactly you are up to, but you can adjust the expression(s), e.g. .//standard2//attributes/attribute[@name='agentname']..hope that helps.
@e-pirate Please, see the updated XML. I need to select what attributes subsection of what particular standardX to search through.
@e-pirate okay, let's approach it differently. Could you post what is your desired output for the presented in the question XML? Thanks.
The .//standard2//attributes/attribute[@name='agentname'] is exactly what I asked for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.