[Solved] Python: XML and Xpath are killing me

Status
Not open for further replies.
I'm trying to run Xpath queries using etree, but I can't seem to figure out the Xpath syntax.
Here's a (sanitized) section of my XML document.
<?xml version="1.0"?>
<Applications>
<Application id="61-X"
displayName="61-X"
type="IHS"
webSiteName="61-X"
environment="X">

<Properties>
<Property name="uploadDir"
value=""/>
<Property name="contentDir"
value="/data01/opt/ihs/ihs61/htdocs/61-heritage-IHS61"/>
</Properties>

<Notification defaultEmail="firstname.lastname@example.com"/>

<Links>
<Link src="/data01/opt/websphere61/AppServer6/profiles/AppSrv01/installedApps/X/233-X.ear/X.war/WEB-INF/classes/application.properties_prod"
dest="/data01/opt/websphere61/AppServer6/profiles/AppSrv01/installedApps/X/233-X.ear/X.war/WEB-INF/classes/application.properties"
userId="was61"
host="X.Y.Z.net" />
<Link src="/data01/opt/websphere61/AppServer6/profiles/AppSrv01/installedApps/X/233-X.ear/X.war/WEB-INF/classes/application.properties_prod"
dest="/data01/opt/websphere61/AppServer6/profiles/AppSrv01/installedApps/X/233-X.ear/X.war/WEB-INF/classes/application.properties"
userId="was61"
host="X.Y.Z.net" />
<!-- DO NOT DELETE: 233-X-NA Link -->
</Links>

</Application>
</Applications>
This XML consists of hundreds of <Application>...</Application> sections.

Here's what I need to do:
1) Query using XML based on some value like the 'id' or 'displayName' and have access to all of the information (i.e. the Application, Properties, Links, etc. sections).
2) Query other values/sections. I assume that this will be obvious once I figure out how to do a basic query. What I'm thinking is the find the correct "Application," then explore the other siblings of that node.
3) This XML is actually fairly large, so I'd like to iterparse() instead of parse(), but I can't get that to work.

Here's what I've tried:
Code:
>>>from lxml import etree
>>>file = open('apps.xml')
>>>tree = etree.parse(file)
>>>test = tree.xpath('//Application[@id="61-X"]')
>>>print(test)
[<Element Application at 1bbf470>]
That successfully finds the node, but I can't figure out how to get any information out of it. The problem seems to be that etree.xpath() returns a list instead of a more complex object that has additional methods/attributes like attrib or get().

Could someone help me figure out what to do with the return from etree.xpath()?

Thanks.
 

Grayrest

Ars Tribunus Militum
2,499
jbrown96":2unpl8mt said:
Here's what I need to do:
1) Query using XML based on some value like the 'id' or 'displayName' and have access to all of the information (i.e. the Application, Properties, Links, etc. sections).
2) Query other values/sections. I assume that this will be obvious once I figure out how to do a basic query. What I'm thinking is the find the correct "Application," then explore the other siblings of that node.
3) This XML is actually fairly large, so I'd like to iterparse() instead of parse(), but I can't get that to work.
Code:
In [1]: from lxml import etree

In [2]: file = open('tmp.xml')

In [3]: tree = etree.parse(file)

In [4]: test = tree.xpath('//Application[@id="61-X"]')[0]

In [5]: test.keys()
Out[5]: ['id', 'displayName', 'type', 'webSiteName', 'environment']

In [6]: list(test)
Out[6]: 
[<Element Properties at 2400510>,
 <Element Notification at 2400540>,
 <Element Links at 2400570>]

In [7]: test.find('Properties')
Out[7]: <Element Properties at 2400510>

In [8]: test.find('.//Property[@name="contentDir"]/@value')[0]
Out[8]: '/data01/opt/ihs/ihs61/htdocs/61-heritage-IHS61'

In [9]: test2 = tree.find('//Application[@id="61-X"]')

In [10]: test2.find('Properties')
Out[10]: <Element Properties at 2400510>
As long as you're finding an element, you can use find() and xpath()[0] more or less interchangably. For non-elements, you have to use the xpath pattern.

You can't use the normal etree api when using iterparse, iterparse produces a more SAX-like interface. See the xml docs for an example.

Finally, I'd recommend using iptyhon. You can type a . and tab complete from there. Also appending a ? (e.g. `test.find?`) will print the docstring.

Late Edit:
jra101":2unpl8mt said:
Code:
results = tree.xpath('//Application[@id="61-X"]')
for node in results:
    print node.attrib["id"]
    print node.attrib["displayName"]
Code:
for node in tree.xpath('//Application[@id="61-X"]'):
    print node['id']
    print node['displayName']
 
Thanks to both of you. I can't believe that I missed the .attrib dictionary.

I have a second question. In my previous query, I was searching for "61-X." The problem is that I don't know or care what the "X" part is. I only know the number. I'd really like to be able to query with '\\Application[@id="61*"]', but that syntax isn't supported.
How can I query with regular expressions?

Thanks.
 

Alamout

Ars Legatus Legionis
27,285
Grayrest":3omtuppq said:
Finally, I'd recommend using iptyhon. You can type a . and tab complete from there. Also appending a ? (e.g. `test.find?`) will print the docstring.
Just to be clear: any decent GUI will do this...heck, IDLE will do it, and that comes with Python.

jbrown96":3omtuppq said:
Thanks to both of you. I can't believe that I missed the .attrib dictionary.

I have a second question. In my previous query, I was searching for "61-X." The problem is that I don't know or care what the "X" part is. I only know the number. I'd really like to be able to query with '\\Application[@id="61*"]', but that syntax isn't supported.
How can I query with regular expressions?
I believe that the library writers recommend not using '.attrib' directly, but instead using .get(attribute_name, default_value=None) because that allows them to change the implementation of attrib (it might not be a dictionary). In practice, I doubt they'll ever change it.

As for regexes: lxml does have some extensions that use regexes, using the EXSLT namespace (bottom of that section).

Or, you can write a simple Python function to parse the field however you like. Here's one I use to ignore case (it uses a lambda function):
Code:
p = etree.parse(xml_path)
f = p.xpath(r'.//data/file[lower(@name)="%s"]' % file_name.lower(),
            extensions={(None,'lower'): (lambda c,a: a[0].lower())})
In your case, you could instead use a function that processes the id attribute with a regex, if you have one that won't fail:
Code:
p = etree.parse(xml_path)
xpath_re = re.compile(r'(\d+)\-.*') # compile it for efficiency
f = p.xpath(r'.//Application[match_no(@id)="%d"]' % number_to_match,
            extensions={(None,'match_no'): (lambda c,a: xpath_re.match(a[0].lower()).group(1))})
If the XML file is very large, check out the lxml website for how to use the target and feed interfaces--it's not as hard as you might think, and they work very efficiently. I think this article was also helpful in understanding how it works.

edit: Oh, I didn't read all of the OP--it's going to be difficult to use those interfaces and also retain the ability to get to neighboring nodes. The whole reason the target/feed combination is so efficient is because it doesn't build the tree--it just walks over it and collects whatever info you're looking for. If you need to keep neighboring nodes around, you'll start to eat up memory. If you just need to find an Application and explore its children, that's fine--finding an Application and exploring its neighbors is harder (and a little weird to me--I generally don't assume that the ordering of nodes in an XML document is important).
 
Alamout":2zhskot5 said:
Grayrest":2zhskot5 said:
Finally, I'd recommend using iptyhon. You can type a . and tab complete from there. Also appending a ? (e.g. `test.find?`) will print the docstring.
Just to be clear: any decent GUI will do this...heck, IDLE will do it, and that comes with Python.

jbrown96":2zhskot5 said:
Thanks to both of you. I can't believe that I missed the .attrib dictionary.

I have a second question. In my previous query, I was searching for "61-X." The problem is that I don't know or care what the "X" part is. I only know the number. I'd really like to be able to query with '\\Application[@id="61*"]', but that syntax isn't supported.
How can I query with regular expressions?
I believe that the library writers recommend not using '.attrib' directly, but instead using .get(attribute_name, default_value=None) because that allows them to change the implementation of attrib (it might not be a dictionary). In practice, I doubt they'll ever change it.

As for regexes: lxml does have some extensions that use regexes, using the EXSLT namespace (bottom of that section).

Or, you can write a simple Python function to parse the field however you like. Here's one I use to ignore case (it uses a lambda function):
Code:
p = etree.parse(xml_path)
f = p.xpath(r'.//data/file[lower(@name)="%s"]' % file_name.lower(),
            extensions={(None,'lower'): (lambda c,a: a[0].lower())})
In your case, you could instead use a function that processes the id attribute with a regex, if you have one that won't fail:
Code:
p = etree.parse(xml_path)
xpath_re = re.compile(r'(\d+)\-.*') # compile it for efficiency
f = p.xpath(r'.//Application[match_no(@id)="%d"]' % number_to_match,
            extensions={(None,'match_no'): (lambda c,a: xpath_re.match(a[0].lower()).group(1))})
If the XML file is very large, check out the lxml website for how to use the target and feed interfaces--it's not as hard as you might think, and they work very efficiently. I think this article was also helpful in understanding how it works.

edit: Oh, I didn't read all of the OP--it's going to be difficult to use those interfaces and also retain the ability to get to neighboring nodes. The whole reason the target/feed combination is so efficient is because it doesn't build the tree--it just walks over it and collects whatever info you're looking for. If you need to keep neighboring nodes around, you'll start to eat up memory. If you just need to find an Application and explore its children, that's fine--finding an Application and exploring its neighbors is harder (and a little weird to me--I generally don't assume that the ordering of nodes in an XML document is important).

Alamout,
I was wondering when you were going to reply to this thread. Thanks for the reply.
From my last thread, you might remember that I was simply trying to get the data out of this terrible XML schema. Mixing the application name with its number and putting data in neighboring nodes are just two of the problems with it.
At this point, I'm not really worried about memory use and speed (all the more reason to move the data!), but thanks for that information.
I appreciate your code examples, but while I understand lambdas, I'm confused by your example. I don't understand the second argument in p.xpath(). It seems to be a dictionary item (with the ":"), but I'm not sure what it does or the variables that it uses. Could you explain it more fully?

Thanks
 

Alamout

Ars Legatus Legionis
27,285
I'm using this ability of the lxml library, which allows you to plug in an arbitrary Python function and call it from inside XPath.

There's actually a third, unspecified component to that XPath call, which is the 'namespaces' parameter. I don't specify a namespace for my extension, so I didn't include it. If you were defining an extension with some generic name, you might want to use one to make sure there were no clashes.

As you noticed, the extensions were passed as a dictionary with one item in it. The key of that dictionary is a tuple specifying the namespace (in this case None, the default) and the function name ('lower' or 'match_no'). The value of the dictionary is the function itself--this could have been a normal function, but I wrote it as a lambda because it's a one-off thing and I'm a smartass. The first argument of the extension is always a 'context object', which I've never bothered with. The other arguments are whatever you pass in via the XPath query.

Having defined an extension dictionary of {(namespace,function_name) : function()}, you can call it in the query using namespace:function_name(). As in my example, you can omit the whole namespace part if you feel like it, it just allows you to keep things neat if there's a lot going on in your code.

I don't know if you noticed my mention of the EXSLT namespace--for your purposes (just doing a simple regex) it would probably be simpler to just use it (this code ripped off from lxml's example, linked earlier):
Code:
regexpNS = "http://exslt.org/regular-expressions" # this is the namespace for the EXSLT extensions

find = etree.XPath("//*[re:test(@id, '4')]", # in this example, we're compiling an XPath query
                   namespaces={'re':regexpNS}) # note the namespace declaration, but there's no extension declaration
                                               # because this function is already present

root = etree.XML('<root><Application id="4"></Application><Application id="5"></Application></root>')

print find(root)[0].get('id')

If you're not worried about memory use, don't worry about iterparse or targets or anything--just parse the whole tree and run your queries on it. When you find a node you're interested in, you'll have access to siblings and stuff like that, to find whatever you need. But if you're dealing with a truly large XML file and memory is limited, you might run into problems.
 
Thanks Alamout. I found the EXSLT namespace stuff, but I couldn't get it to work. I do have it working now, and it appears to do everything that I need!

Code:
>>> from lxml import etree
>>> tree = etree.parse('admin_applications.xml')
>>> result = tree.xpath("//*[re:test(@id, '9467')]", namespaces={'re':'http://exslt.org/regular-expressions'})
>>> print(result)
[<Element Application at 1e662b8>, <Element Application at 1e66310>]
>>> result[0].getchildren()
[<Element Properties at 1e66368>, <Element WARS at 1e663c0>, <Element Notification at 1e66418>, <Element Links
 at 1e66470>]
I think that I'm best off with the EXSLT method because it seems to be far simpler. I can find applications and all the associated information. I do have a couple questions about what's happeing:
1) In the Xpath query, I know what "re:" does, but I don't get why "test" is in there.
2) What is http://exslt.org/regular-expressions. The address doesn't resolve to anything. Is this just normal regex matching rules?
 

Grayrest

Ars Tribunus Militum
2,499
jbrown96":jmmhjk7r said:
I do have a couple questions about what's happeing:
1) In the Xpath query, I know what "re:" does, but I don't get why "test" is in there.
2) What is http://exslt.org/regular-expressions. The address doesn't resolve to anything. Is this just normal regex matching rules?

The url 'http://exslt.org/regular-expressions' is an XML namespace. Many well known namespaces have landing pages at the url but this one doesn't. exslt regexp api.

Think of 're' as a local alias for that url. When an xml parser reads `re:test` it expands it out to `http://exslt.org/regular-expressions/test`, which is unambiguously unique so the xpath engine knows exactly which function you mean. I'm sure I have the vocabulary and details wrong, but that's the general idea.

A minor perf point in this case, but you should root (^ or $) regular expressions that are going to be run over a lot of data when possible. If a regexp is rooted and fails to match, it fails. If an unrooted regexp fails to match, the regexp engine will work through the string to be matched character by character.
 
Status
Not open for further replies.