0

我正在使用 lxml 在标签中使用破折号来客观化 xml 字符串。

例如:

from lxml import objectify
xml_string = """<root>
                   <foo-foo name="example" foo-description="description">
                       <bar doc-name="name" />
                       <test tag="test" />
                    </foo-foo>
                </root>"""
obj = objectify.fromstring(xml_string)

在这一步之后,元素的名称带有破折号。foo-foo由于名称中的破折号,我无法访问。

如何从标签名称和属性名称中删除破折号?

4

2 回答 2

1

这很 hacky,但您可以执行以下操作将-in 元素名称转换为 a _

from lxml import etree
from lxml import objectify

xml_string = """<root>
                   <foo-foo name="example" foo-description="description">
                       <bar doc-name="name" />
                       <test tag="test" />
                    </foo-foo>
                </root>"""

doc = etree.fromstring(xml_string)
for tag in doc.iter():
    if '-' in tag.tag:
        tag.tag = tag.tag.replace('-', '_')

obj = objectify.fromstring(etree.tostring(doc))

特别是,我认为可能有一种更好的方法可以将已解析的 XML 文档doc转换为对象化版本,而无需转储和重新解析 XML,但这是我能在短时间内想到的最好方法。

于 2021-08-11T11:58:27.457 回答
0

这可以通过 ElementTree 来完成

from xml.etree import ElementTree as ET

xml = """<foo-foo name="example" foo-description="description">
                   <bar doc-name="name" />
                    <test tag="test" />
                </foo-foo>"""

foo_foo = ET.fromstring(xml)
print(f'name: {foo_foo.attrib["name"]}')
print(f'bar dic name: {foo_foo.find("bar").attrib["doc-name"]}')
print(f'test tag: {foo_foo.find("test").attrib["tag"]}')

输出

name: example
bar dic name: name
test tag: test
于 2021-08-11T11:33:43.157 回答