Xml в массив python

xmljson 0.2.1

Converts XML into JSON/Python dicts/arrays and vice-versa.

Ссылки проекта

Статистика

Метаданные

Лицензия: MIT License (MIT)

Сопровождающие

Классификаторы

Описание проекта

This library is not actively maintained. Alternatives are xmltodict and untangle. Use only if you need to parse using specific XML to JSON conventions.

xmljson converts XML into Python dictionary structures (trees, like in JSON) and vice-versa.

About

XML can be converted to a data structure (such as JSON) and back. For example:

can be converted into this data structure (which also a valid JSON object):

This uses the BadgerFish convention that prefixes attributes with @ . The conventions supported by this library are:

  • Abdera: Use «attributes» for attributes, «children» for nodes
  • BadgerFish: Use «$» for text content, @ to prefix attributes
  • Cobra: Use «attributes» for sorted attributes (even when empty), «children» for nodes, values are strings
  • GData: Use «$t» for text content, attributes added as-is
  • Parker: Use tail nodes for text content, ignore attributes
  • Yahoo Use «content» for text content, attributes added as-is
Читайте также:  Сортировка массива вставками php

Convert data to XML

To convert from a data structure to XML using the BadgerFish convention:

>>> from xmljson import badgerfish as bf >>> bf.etree(>)

This returns an array of etree.Element structures. In this case, the result is identical to:

>>> from xml.etree.ElementTree import fromstring >>> [fromstring('

Hellobold

')]

The result can be inserted into any existing root etree.Element:

>>> from xml.etree.ElementTree import Element, tostring >>> result = bf.etree(>, root=Element('root')) >>> tostring(result) ''
>>> from lxml.html import Element, tostring >>> result = bf.etree(>, root=Element('html')) >>> tostring(result, doctype='') '\n '

For ease of use, strings are treated as node text. For example, both the following are the same:

By default, non-string values are converted to strings using Python’s str , except for booleans – which are converted into true and false (lower case). Override this behaviour using xml_fromstring :

>>> tostring(bf.etree(, root=Element('root'))) 'true1.23' >>> from xmljson import BadgerFish # import the class >>> bf_str = BadgerFish(xml_tostring=str) # convert using str() >>> tostring(bf_str.etree(, root=Element('root'))) 'True1.23'

If the data contains invalid XML keys, these can be dropped via invalid_tags=’drop’ in the constructor:

>>> bf_drop = BadgerFish(invalid_tags='drop') >>> data = bf_drop.etree(, root=Element('root')) # Drops invalid tag >>> tostring(data) '11'

Convert XML to data

To convert from XML to a data structure using the BadgerFish convention:

>>> bf.data(fromstring('

Hellobold

')) >>

To convert this to JSON, use:

>>> from json import dumps >>> dumps(bf.data(fromstring('

Hellobold

'))) ', "@id": "main", "$": "Hello">>'

To preserve the order of attributes and children, specify the dict_type as OrderedDict (or any other dictionary-like type) in the constructor:

>>> from collections import OrderedDict >>> from xmljson import BadgerFish # import the class >>> bf = BadgerFish(dict_type=OrderedDict) # pick dict class

By default, values are parsed into boolean, int or float where possible (except in the Yahoo method). Override this behaviour using xml_fromstring :

>>> dumps(bf.data(fromstring('1'))) '>' >>> bf_str = BadgerFish(xml_fromstring=False) # Keep XML values as strings >>> dumps(bf_str.data(fromstring('1'))) '>' >>> bf_str = BadgerFish(xml_fromstring=repr) # Custom string parser '>'

xml_fromstring can be any custom function that takes a string and returns a value. In the example below, only the integer 1 is converted to an integer. Everything else is retained as a float:

>>> def convert_only_int(val): . return int(val) if val.isdigit() else val >>> bf_int = BadgerFish(xml_fromstring=convert_only_int) >>> dumps(bf_int.data(fromstring('

12.5NaN

'))) ', "y": , "z": >>'

Conventions

To use a different conversion method, replace BadgerFish with one of the other classes. Currently, these are supported:

>>> from xmljson import abdera # == xmljson.Abdera() >>> from xmljson import badgerfish # == xmljson.BadgerFish() >>> from xmljson import cobra # == xmljson.Cobra() >>> from xmljson import gdata # == xmljson.GData() >>> from xmljson import parker # == xmljson.Parker() >>> from xmljson import yahoo # == xmljson.Yahoo()

Options

Conventions may support additional options.

The Parker convention absorbs the root element by default. parker.data(preserve_root=True) preserves the root instance:

>>> from xmljson import parker, Parker >>> from xml.etree.ElementTree import fromstring >>> from json import dumps >>> dumps(parker.data(fromstring('12'))) '' >>> dumps(parker.data(fromstring('12'), preserve_root=True)) '<"x": >'

Installation

This is a pure-Python package built for Python 2.7+ and Python 3.0+. To set up:

Simple CLI utility

After installation, you can benefit from using this package as simple CLI utility. By now only XML to JSON conversion supported. Example:

$ python -m xmljson -h usage: xmljson [-h] [-o OUT_FILE] [-d ] [in_file] positional arguments: in_file defaults to stdin optional arguments: -h, —help show this help message and exit -o OUT_FILE, —out_file OUT_FILE defaults to stdout -d , —dialect defaults to parker $ python -m xmljson -d parker tests/mydata.xml

This is a typical UNIX filter program: it reads file (or stdin ), processes it in some way (convert XML to JSON in this case), then prints it to stdout (or file). Example with pipe:

$ some-xml-producer | python -m xmljson | some-json-processor

There is also pip ’s console_script entry-point, you can call this utility as xml2json :

$ xml2json -d abdera mydata.xml

Roadmap

  • Test cases for Unicode
  • Support for namespaces and namespace prefixes
  • Support XML comments

History

0.2.1 (25 Apr 2020)

  • Bugfix: Don’t strip whitespace in xml text values (@imoore76)
  • Bugfix: Yahoo convention should convert 0 into . Empty elements become » not <>
  • Suggest alternate libraries in documentation

0.2.0 (21 Nov 2018)

  • xmljson command line script converts from XML to JSON (@tribals)
  • invalid_tags=’drop’ in the constructor drops invalid XML tags in .etree() (@Zurga)
  • Bugfix: Parker converts to instead of None (@jorndoe #29)

0.1.9 (1 Aug 2017)

0.1.8 (9 May 2017)

  • Add Abdera and Cobra conventions
  • Add Parker.data(preserve_root=True) option to preserve root element in Parker convention.

0.1.6 (18 Feb 2016)

  • Add xml_fromstring= and xml_tostring= parameters to constructor to customise string conversion from and to XML.

0.1.5 (23 Sep 2015)

0.1.4 (20 Sep 2015)

0.1.3 (20 Sep 2015)

  • Simplify > to in BadgerFish and GData conventions.
  • Add test cases for .etree() – mainly from the MDN JXON article.
  • dict_type / list_type do not need to inherit from dict / list

0.1.2 (18 Sep 2015)

  • Always use the dict_type class to create dictionaries (which defaults to OrderedDict to preserve order of keys)
  • Update documentation, test cases
  • Remove support for Python 2.6 (since we need collections.Counter )
  • Make the Travis CI build pass

0.1.1 (18 Sep 2015)

  • Convert true , false and numeric values from strings to Python types
  • xmljson.parker.data() is compliant with Parker convention (bugs resolved)

0.1.0 (15 Sep 2015)

Источник

Парсинг XML Python

Xml парсинг

Вы когда-нибудь сталкивались с надоедливым XML-файлом, который вам нужно проанализировать, чтобы получить важные значения? Давайте узнаем, как создать парсер Python XML.

Мы рассмотрим, как мы можем анализировать подобные XML-файлы с помощью Python, чтобы получить соответствующие атрибуты и значения.

Метод 1: Использование ElementTree (рекомендуется)

Мы можем использовать библиотеку ElementTree Python для решения этой задачи.

Это самый простой и рекомендуемый вариант для создания синтаксического анализатора Python XML, поскольку эта библиотека по умолчанию входит в состав Python.

Она не только обеспечивает легкий доступ, поскольку уже установлена, но и работает довольно быстро. Давайте посмотрим, как именно мы можем извлечь атрибуты из нашего тестового файла.

Мы будем использовать интерфейс xml.etree.ElementTree внутри основного xml пакета.

import xml.etree.ElementTree as ET

Дерево синтаксического анализатора

Давайте сначала построим корневой узел этого дерева синтаксического анализа. Это самый верхний узел, он необходим нам для начала синтаксического анализа.

К счастью для нас, в этом API уже есть следующий метод:

import xml.etree.ElementTree as ET root_node = ET.parse('sample.xml').getroot() print(root_node)

Это автоматически прочитает входной XML-файл и получит для нас корневой узел.

Похоже, он проанализирован. Но мы пока не можем это проверить. Итак, давайте проанализируем другие атрибуты и попробуем получить значение.

Получение значения соответствующих атрибутов

Итак, теперь наша задача — получить значение внутри атрибута с помощью нашего Python XML Parser.

Его позиция от корневого узла — , поэтому нам нужно перебрать все совпадения на этом уровне дерева.

Мы можем сделать это с помощью root_node.findall(level) , где level — это желаемая позиция (в нашем случае ).

for tag in root_node.find_all(level): value = tag.get(attribute) if value is not None: print(value)

tag.get(attribute) получит значение нашего на уровнях, на которых мы ищем. Итак, нам просто нужно сделать это в и получить значения атрибутов и . Это оно!

import xml.etree.ElementTree as ET # We're at the root node () root_node = ET.parse('sample.xml').getroot() # We need to go one level below to get # and then one more level from that to go to for tag in root_node.findall('header/type'): # Get the value of the heading attribute h_value = tag.get('heading') if h_value is not None: print(h_value) # Get the value of the text attribute t_value = tag.get('text') if t_value is not None: print(t_value)
XML Parsing in Python Hello from AskPython. We'll be parsing XML

Мы получили все значения на этом уровне нашего дерева синтаксического анализа XML! Мы успешно проанализировали наш XML-файл.

Возьмем другой пример, чтобы все прояснить.

Теперь предположим, что XML-файл выглядит так:

Здесь мы должны не только получить значения атрибутов name , но также получить текстовые значения 10, 20, 30 и 40 для каждого элемента на этом уровне.

Чтобы получить значение атрибута name , мы можем сделать то же самое, что и раньше. Мы также можем использовать tag.attrib[name] чтобы получить значение. Это то же самое, что и tag.get(name) , за исключением того, что он использует поиск по словарю.

attr_value = tag.get(attr_name) # Both methods are the same. You can # choose any approach attr_value = tag.attrib[attr_name]

Получить текстовое значение просто. Просто используйте:

Итак, наша полная программа для этого парсера будет:

import xml.etree.ElementTree as ET # We're at the root node () root_node = ET.parse('sample.xml').getroot() # We need to go one level below to get # and then one more level from that to go to for tag in root_node.findall('items/item'): # Get the value from the attribute 'name' value = tag.attrib['name'] print(value) # Get the text of that tag print(tag.text)
item1 10 item2 20 item3 30 item4 40

Вы можете расширить эту логику на любое количество уровней и для файлов XML произвольной длины! Вы также можете записать новое дерево синтаксического анализа в другой файл XML.

Метод 2: использование BeautifulSoup (надежный)

Это также еще один хороший выбор, если по какой-то причине исходный XML плохо отформатирован. XML может работать не очень хорошо, если вы не выполните предварительную обработку файла.

Оказывается, BeautifulSoup очень хорошо работает со всеми этими типами файлов, поэтому, если вы хотите проанализировать любой XML-файл, используйте этот подход.

Чтобы установить его, используйте pip и установите модуль bs4 :

Я дам вам небольшой фрагмент нашего предыдущего XML-файла:

Я передам этот файл, а затем bs4 его с помощью bs4 .

from bs4 import BeautifulSoup fd = open('sample.xml', 'r') xml_file = fd.read() soup = BeautifulSoup(xml_file, 'lxml') for tag in soup.findAll("item"): # print(tag) print(tag["name"]) print(tag.text) fd.close()

Синтаксис аналогичен нашему модулю xml , поэтому мы по-прежнему получаем имена атрибутов, используя value = tag[‘attribute_name’] и text = tag.text . Точно так же, как и раньше!

item1 10 item2 20 item3 30 item4 40

Мы также проанализировали это с помощью bs4 ! Если ваш исходный XML файл плохо отформатирован, можно использовать этот метод, поскольку BeautifulSoup имеет другие правила для обработки таких файлов.

Источник

Оцените статью