Nick H
Nick H

Reputation: 123

Search for specific XML element Attribute values

Using Python ElementTree to construct and edit test messages:

Part of XML as follows:

<FIXML>
<TrdMtchRpt TrdID="$$+TrdID#" RptTyp="0" TrdDt="20120201" MtchTyp="4" LastMkt="ABCD" LastPx="104.11">

The key TrdID contain values beginning with $$ to identify that this value is variable data and needs to be amended once the message is constructed from a template, in this case to the next sequential number (stored in a dictionary - the overall idea is to load a dictionary from a file with the attribute key listed and the associated value such as the next sequential number e.g. dictionary file contains $$+TrdID# 12345 using space as the delim).

So far my script iterates the parsed XML and examines each indexed element in turn. There will be several fields in the xml file that require updating so I need to avoid using hard coded references to element tags.

How can I search the element/attribute to identify if the attribute contains a key where the corresponding value starts with or contains the specific string $$?

And for reasons unknown to me we cannot use lxml!

Upvotes: 1

Views: 1881

Answers (2)

ranendra
ranendra

Reputation: 2512

You can use ElementTree package. It gives you an object with a hierarchical data structure from XML document.

Upvotes: 1

user647772
user647772

Reputation:

You can use XPath.

import lxml.etree as etree
import StringIO from StringIO

xml = """<FIXML>
           <TrdMtchRpt TrdID="$$+TrdID#"
                       RptTyp="0"
                       TrdDt="20120201"
                       MtchTyp="4"
                       LastMkt="ABCD"
                       LastPx="104.11"/>
         </FIXML>"""

tree = etree.parse(StringIO(xml))

To find elements TrdMtchRpt where the attribute TrdID starts with $$:

r = tree.xpath("//TrdMtchRpt[starts-with(@TrdID, '$$')]")
r[0].tag == 'TrdMtchRpt'
r[0].get("TrdID") == '$$+TrdID#'

If you want to find any element where at least one attribute starts with $$ you can do this:

r = tree.xpath("//*[starts-with(@*, '$$')]")
r[0].tag == 'TrdMtchRpt'
r[0].get("TrdID") == '$$+TrdID#'

Look at the documentation:

Upvotes: 1

Related Questions