-
Hi, I'm currently giving BigXML a go, and I'm loving it so far. However I'm currently stumped on the subject of iterating through all sub-elements. For example, here's a test XML:
Let's say I want the list of all the cats I have, as well as the name of the tags (name1 and name2). Rather than explicitly set the subnode names in the handler (which would not be practical if there's a lot of subnodes), is there a way to iterate the subnodes at the level? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hello, currently this was not a targeted use case, so the way to do it is not optimal nor documented. I'm wondering if this use case is really prevalent, as usually XML documents tends to follow a specific schema. If you have public XML items that fall into this use case, please share them so that I have a better understanding of real-world examples. The usual way would be as you said to explicitly set the subnode names when defining the handler, by chaining the decorators: @xml_handle_element("animals", "cats", "name1")
@xml_handle_element("animals", "cats", "name2")
def handle_cats_names(node):
yield (node.name, node.text) >>> with open('animals.xml', 'rb') as f:
... for item in Parser(f).iter_from(handle_cats_names):
... print(item)
...
('name1', 'Baron Cat')
('name2', 'Fireball') However the following alternative is possible. First, define a handler with no decorator (we filter on def generic_handle(node):
if isinstance(node, XMLElement):
yield (node.name, node.text) Then use it at the @xml_handle_element("animals", "cats")
def handle_cats(node):
yield from node.iter_from(generic_handle) At this point the following should work: >>> with open('animals.xml', 'rb') as f:
... for item in Parser(f).iter_from(handle_cats):
... print(item)
...
('name1', 'Baron Cat')
('name2', 'Fireball') |
Beta Was this translation helpful? Give feedback.
Hello, currently this was not a targeted use case, so the way to do it is not optimal nor documented.
I'm wondering if this use case is really prevalent, as usually XML documents tends to follow a specific schema.
If you have public XML items that fall into this use case, please share them so that I have a better understanding of real-world examples.
The usual way would be as you said to explicitly set the subnode names when defining the handler, by chaining the decorators: