1

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!

2 Answers 2

1

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:

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

3 Comments

Thanks @Tichodroma, I've editied my query to be more specific, unfortunately I am not allowed to use lxml. Regards.
Thanks, seems this python learning exercise is learning what I cannot do with the tools I've been given! Regards.
Can up with a simple solution where: for val in xmlelement.attrib.iteritems(): slice = val[0:2] if slice = "$$": dosomething else: checknextelement
1

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

Comments

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.