Python l xml tostring not print nsmap - PullRequest
       16

Python l xml tostring not print nsmap

0 голосов
/ 07 апреля 2020

Я работаю в парсере Doxygen XML. Моя проблема на самом деле проста, мне нужно использовать L XML tostring, чтобы получить необработанное содержимое элемента XML.

У меня это работает с ETree, но я переключился на LMXL так Я получаю strip_tags.

Допустим, у меня есть этот XML файл:

<?xml version='1.0' encoding='UTF-8' standalone='no'?>
<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="compound.xsd" version="1.8.16">
  <child2/>
  <child3/>
</root>

И я делаю это:

tree = ET.parse('new1.xml')
root = tree.getroot()
child3 = root.find("./child3")

objectify.deannotate(child3, cleanup_namespaces=True, xsi=True, pytype=True)
etree.cleanup_namespaces(child3)
child3.nsmap.clear()
etree.strip_attributes(child3, 'nsmap') 

print(ET.tostring(child3, encoding='unicode', pretty_print=True))

Это то, что я получаю :

<child3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>

Это то, что я ХОЧУ:

<child3/>

Можно ли добавить tostring в NOT print nsmap?

Я пытался :

Если я попытаюсь

root.nsmap = None

, я получу исключение:

AttributeError: attribute 'nsmap' of 'lxml.etree._Element' objects is not writable

Я использую Python 3,7 64 бит с Windows 10.

Спасибо.

1 Ответ

1 голос
/ 09 апреля 2020

В документе XML используется пространство имен http://www.w3.org/2001/XMLSchema. Атрибут xsi:noNamespaceSchemaLocation связан с этим пространством имен.

Чтобы получить требуемый вывод, вы должны 1) удалить атрибут xsi:noNamespaceSchemaLocation и 2) удалить объявление пространства имен.

from lxml import etree

tree = etree.parse('new1.xml')
root = tree.getroot()

# Remove the xsi:noNamespaceSchemaLocation attribute
del root.attrib["{http://www.w3.org/2001/XMLSchema-instance}noNamespaceSchemaLocation"]

# Remove the declaration for the now unused namespace. Must be done on the root element
etree.cleanup_namespaces(root)

child3 = root.find("./child3")

# Print child3
print(etree.tostring(child3, encoding='unicode', pretty_print=True))

# Print the whole document
print(etree.tostring(root, encoding='unicode', pretty_print=True))

Выход:

<child3/>


<root version="1.8.16">
  <child2/>
  <child3/>
</root>
...