1
0
mirror of https://github.com/scrapy/scrapy.git synced 2025-02-25 04:04:21 +00:00

XmlItemExporter: added built-in support for exporting multi-valued fields (for convenience)

This commit is contained in:
Pablo Hoffman 2009-09-14 22:05:52 -03:00
parent e8960bf616
commit 56b292e057
3 changed files with 34 additions and 1 deletions

View File

@ -240,6 +240,26 @@ XmlItemExporter
</item>
</items>
Unless overriden in :meth:`serialize_field` method, multi-valued fields are
exported by serializing each value inside a ``<value>`` element. This is for
convenience, as multi-valued fields are very common.
For example, the item::
Item(name=['John', 'Doe'], age='23')
Would be serialized as::
<?xml version="1.0" encoding="utf-8"?>
<items>
<item>
<name>
<value>John</value>
<value>Doe</value>
</name>
<age>23</age>
</item>
</items>
CsvItemExporter
---------------

View File

@ -95,6 +95,10 @@ class XmlItemExporter(BaseItemExporter):
def _export_xml_field(self, name, serialized_value):
self.xg.startElement(name, {})
if hasattr(serialized_value, '__iter__'):
for value in serialized_value:
self._export_xml_field('value', value)
else:
self.xg.characters(serialized_value)
self.xg.endElement(name)

View File

@ -137,6 +137,15 @@ class XmlItemExporterTest(BaseItemExporterTest):
expected_value = '<?xml version="1.0" encoding="utf-8"?>\n<items><item><age>22</age><name>John\xc2\xa3</name></item></items>'
self.assertEqual(self.output.getvalue(), expected_value)
def test_multivalued_fields(self):
output = StringIO()
item = TestItem(name=[u'John\xa3', u'Doe'])
ie = XmlItemExporter(output)
ie.start_exporting()
ie.export_item(item)
ie.finish_exporting()
expected_value = '<?xml version="1.0" encoding="utf-8"?>\n<items><item><name><value>John\xc2\xa3</value><value>Doe</value></name></item></items>'
self.assertEqual(output.getvalue(), expected_value)
class JsonLinesItemExporterTest(BaseItemExporterTest):