James the Great
James the Great

Reputation: 951

Example with PyXB: Generate Python code and obtain Attribute value within XML Element

I am having a hard time getting started with PyXB.

Let's use this XML file for example:

<?xml version="1.0"?>
<purchaseOrder orderDate="1999-10-20">
  <shipTo country="US">
    <name>Alice Smith</name>
    <street>123 Maple Street</street>
    <city>Anytown</city><state>AK</state><zip>12341</zip>
  </shipTo>
  <billTo country="US">
    <name>Robert Smith</name>
    <street>8 Oak Avenue</street>
    <city>Anytown</city><state>AK</state><zip>12341</zip>
  </billTo>
</purchaseOrder>

Say if I managed to create the Python library pol.py:

Python code

import po1
xml = open('po1.xml').read()
order = po1.CreateFromDocument(xml)

I understand that I can obtain content within Element (eg. order.billTo.name = Robert Smith), but how do I obtain the value from Attribute "country" (which is "US")?

Thanks in advance!

Reference: http://pyxb.sourceforge.net/userref_pyxbgen.html

Upvotes: 0

Views: 1512

Answers (1)

pabigot
pabigot

Reputation: 989

XML attributes are exposed by PyXB as Python attributes in exactly the same way that XML elements are exposed as Python attributes. So you just do:

print(order.billTo.name)
print(order.billTo.country)

In XML, attributes and elements are in different namespaces while in Python they share a namespace, so if the same name is used for both an attribute and an element the attribute will be renamed by PyXB. A diagnostic is emitted when the binding is generated in this case. See Deconflicting Names for details on this process.

Upvotes: 3

Related Questions