Xml parser python module

20.4. XML Processing Modules¶

Python’s interfaces for processing XML are grouped in the xml package.

The XML modules are not secure against erroneous or maliciously constructed data. If you need to parse untrusted or unauthenticated data see the XML vulnerabilities and The defusedxml and defusedexpat Packages sections.

It is important to note that modules in the xml package require that there be at least one SAX-compliant XML parser available. The Expat parser is included with Python, so the xml.parsers.expat module will always be available.

The documentation for the xml.dom and xml.sax packages are the definition of the Python bindings for the DOM and SAX interfaces.

The XML handling submodules are:

  • xml.etree.ElementTree : the ElementTree API, a simple and lightweight XML processor
  • xml.dom : the DOM API definition
  • xml.dom.minidom : a minimal DOM implementation
  • xml.dom.pulldom : support for building partial DOM trees
  • xml.sax : SAX2 base classes and convenience functions
  • xml.parsers.expat : the Expat parser binding

20.4.1. XML vulnerabilities¶

The XML processing modules are not secure against maliciously constructed data. An attacker can abuse XML features to carry out denial of service attacks, access local files, generate network connections to other machines, or circumvent firewalls.

The following table gives an overview of the known attacks and whether the various modules are vulnerable to them.

  1. xml.etree.ElementTree doesn’t expand external entities and raises a ParserError when an entity occurs.
  2. xml.dom.minidom doesn’t expand external entities and simply returns the unexpanded entity verbatim.
  3. xmlrpclib doesn’t expand external entities and omits them.

The documentation for defusedxml on PyPI has further information about all known attack vectors with examples and references.

20.4.2. The defusedxml and defusedexpat Packages¶

defusedxml is a pure Python package with modified subclasses of all stdlib XML parsers that prevent any potentially malicious operation. Use of this package is recommended for any server code that parses untrusted XML data. The package also ships with example exploits and extended documentation on more XML exploits such as XPath injection.

defusedexpat provides a modified libexpat and a patched pyexpat module that have countermeasures against entity expansion DoS attacks. The defusedexpat module still allows a sane and configurable amount of entity expansions. The modifications may be included in some future release of Python, but will not be included in any bugfix releases of Python because they break backward compatibility.

Table Of Contents

Источник

XML Processing Modules¶

Python’s interfaces for processing XML are grouped in the xml package.

Читайте также:  Тип данных bigint javascript

The XML modules are not secure against erroneous or maliciously constructed data. If you need to parse untrusted or unauthenticated data see the XML vulnerabilities and The defusedxml Package sections.

It is important to note that modules in the xml package require that there be at least one SAX-compliant XML parser available. The Expat parser is included with Python, so the xml.parsers.expat module will always be available.

The documentation for the xml.dom and xml.sax packages are the definition of the Python bindings for the DOM and SAX interfaces.

The XML handling submodules are:

  • xml.etree.ElementTree : the ElementTree API, a simple and lightweight XML processor
  • xml.dom : the DOM API definition
  • xml.dom.minidom : a minimal DOM implementation
  • xml.dom.pulldom : support for building partial DOM trees
  • xml.sax : SAX2 base classes and convenience functions
  • xml.parsers.expat : the Expat parser binding

XML vulnerabilities¶

The XML processing modules are not secure against maliciously constructed data. An attacker can abuse XML features to carry out denial of service attacks, access local files, generate network connections to other machines, or circumvent firewalls.

The following table gives an overview of the known attacks and whether the various modules are vulnerable to them.

Vulnerable (1)

Vulnerable (1)

Vulnerable (1)

Vulnerable (1)

Vulnerable (1)

Vulnerable (1)

Vulnerable (1)

Vulnerable (1)

Vulnerable (1)

Vulnerable (1)

external entity expansion

  1. Expat 2.4.1 and newer is not vulnerable to the “billion laughs” and “quadratic blowup” vulnerabilities. Items still listed as vulnerable due to potential reliance on system-provided libraries. Check pyexpat.EXPAT_VERSION .
  2. xml.etree.ElementTree doesn’t expand external entities and raises a ParserError when an entity occurs.
  3. xml.dom.minidom doesn’t expand external entities and simply returns the unexpanded entity verbatim.
  4. xmlrpclib doesn’t expand external entities and omits them.
  5. Since Python 3.7.1, external general entities are no longer processed by default.

The Billion Laughs attack – also known as exponential entity expansion – uses multiple levels of nested entities. Each entity refers to another entity several times, and the final entity definition contains a small string. The exponential expansion results in several gigabytes of text and consumes lots of memory and CPU time.

quadratic blowup entity expansion

A quadratic blowup attack is similar to a Billion Laughs attack; it abuses entity expansion, too. Instead of nested entities it repeats one large entity with a couple of thousand chars over and over again. The attack isn’t as efficient as the exponential case but it avoids triggering parser countermeasures that forbid deeply nested entities.

external entity expansion

Entity declarations can contain more than just text for replacement. They can also point to external resources or local files. The XML parser accesses the resource and embeds the content into the XML document.

Читайте также:  Среднее значение всех элементов массива java

Some XML libraries like Python’s xml.dom.pulldom retrieve document type definitions from remote or local locations. The feature has similar implications as the external entity expansion issue.

Decompression bombs (aka ZIP bomb) apply to all XML libraries that can parse compressed XML streams such as gzipped HTTP streams or LZMA-compressed files. For an attacker it can reduce the amount of transmitted data by three magnitudes or more.

The documentation for defusedxml on PyPI has further information about all known attack vectors with examples and references.

The defusedxml Package¶

defusedxml is a pure Python package with modified subclasses of all stdlib XML parsers that prevent any potentially malicious operation. Use of this package is recommended for any server code that parses untrusted XML data. The package also ships with example exploits and extended documentation on more XML exploits such as XPath injection.

Источник

Парсинг 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-файл.

Читайте также:  Шапка на css grid

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

Теперь предположим, что 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 имеет другие правила для обработки таких файлов.

Источник

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