Using PyXB, I'd like to serialize a sub node and then be able to parse it back. The naive way isn't working, because the sub node is not a valid root element according to the schema.
My schema:
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="root" type="Root"/>
<xsd:complexType name="Root">
<xsd:sequence>
<xsd:element name="item" maxOccurs="unbounded" type="Item"/>
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="Item">
<xsd:sequence>
<xsd:element name="val"/>
</xsd:sequence>
</xsd:complexType>
</xsd:schema>
And sample XML:
<?xml version="1.0" encoding="utf-8"?>
<root>
<item>
<val>1</val>
</item>
<item>
<val>2</val>
</item>
<item>
<val>3</val>
</item>
</root>
I need to be able to serialize a specific item and then load it back. Something like this:
>>> root = CreateFromDocument(sample)
# locate a sub node to serialize
>>> root.item[1].toxml()
'<?xml version="1.0" ?><item><val>2</val></item>'
# load the sub node, getting an Item back
>>> sub_node = CreateFromDocument('<?xml version="1.0" ?><item><val>2</val></item>')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "binding.py", line 63, in CreateFromDocument
instance = handler.rootObject()
File "pyxb/binding/saxer.py", line 285, in rootObject
raise pyxb.UnrecognizedDOMRootNodeError(self.__rootObject)
pyxb.exceptions_.UnrecognizedDOMRootNodeError: <pyxb.utils.saxdom.Element object at 0x7f30ba4ac550>
# or, perhaps, some kind of unique identifier:
>>> root.item[1].hypothetical_unique_identifier()
'//root/item/1'
>>> sub_node = CreateFromDocument(sample).find_node('//root/item/1')
<binding.Item object at 0x7f30ba4a5d50>
This of course doesn't work because item
can't be root node according to the schema. Is there a way to parse just a sub tree, getting an Item instead back?
Alternatively, is there some way to uniquely identify a sub node so I can find it later?