我想从XML中获得一些信息。
如果type-v2="text"
这是XML代码:
<dashboards>
<dashboard name="1 off">
<style/>
<size maxheight="800" maxwidth="1000" minheight="800" minwidth="1000"/>
<zones>
<zone h="100000" id="2" type-v2="layout-basic" w="100000" x="0" y="0">
<zone forceUpdate="true" h="98000" id="1" type-v2="text" w="49200" x="800" y="1000">
<formatted-text>
<run fontsize="1">
row 1
</run>
<run>
Æ
</run>
<run fontsize="2">
row 2
</run>
</formatted-text>
<zone-style>
<format attr="border-color" value="#000000"/>
<format attr="border-style" value="none"/>
<format attr="border-width" value="0"/>
<format attr="margin" value="4"/>
</zone-style>
</zone>
<zone h="98000" id="3" type-v2="text" w="49200" x="50000" y="1000">
<formatted-text>
<run>
id2
</run>
</formatted-text>
<zone-style>
<format attr="border-color" value="#000000"/>
<format attr="border-style" value="none"/>
<format attr="border-width" value="0"/>
<format attr="margin" value="4"/>
</zone-style>
</zone>
<zone-style>
<format attr="border-color" value="#000000"/>
<format attr="border-style" value="none"/>
<format attr="border-width" value="0"/>
<format attr="margin" value="8"/>
</zone-style>
</zone>
</zones>
</dashboard>
</dashboards>我能够分别获得所有in和所有细节,但我希望得到不同的输出。因此,对于每个元素,我想给它分配父id。
这是我的代码,分别获取信息:
import xml.etree.ElementTree as et
tree = et.parse(r'C:\book3.twb')
root = tree.getroot()
dbnameRC=[]
fontRC = []
sizeRC = []
weightRC = []
f_styleRC = []
decoRC = []
colorRC= []
alignRC = []
textcontRC=[]
idRC=[]
for db in root.iter("dashboard"):
root1 = db
for z in root1.findall(".//zone[@type-v2='text']"):
idRC.append(z.get('id'))
for m in root1.findall(".//zone[@type-v2='text']/formatted-text//run"):
weightRC.append(m.get('bold'))
alignRC.append(m.get('fontalignment'))
colorRC.append(m.get('fontcolor'))
fontRC.append(m.get('fontname'))
sizeRC.append(m.get('fontsize'))
f_styleRC.append(m.get('italic'))
decoRC.append(m.get('underline'))
dbnameRC.append(db.attrib['name'])
textcontRC.append(m.text)1. idRC的输出是:
['1', '3'] 这是正确的,因为我们只有两个is类型-v2=‘text’]
['1', None, '2', None]这也是正确的。
问题是如何编写代码作为输出,如下所示:

基本上,我想要做的就是输入-v2=“text”类型的区域,获取它的id,并将所有的undernath分配给这个特定的id,而不是移动到另一个具有不同id和
输入-v2=“text”,并在此区域下运行所有代码。
发布于 2022-02-17 11:42:23
而不是您的第二个root1.findall(),您可以zone.findall()代替-允许您分组的id与每次运行。
runs = []
for db in root.iter("dashboard"):
root1 = db
for zone in root1.findall(".//zone[@type-v2='text']"):
idrc = zone.get('id')
for run in zone.findall("./formatted-text//run"):
runs.append([
idrc,
run.get("bold"),
run.get("fontalignment"),
run.get("fontcolor"),
run.get("fontname"),
run.get("fontsize"),
run.get("italic"),
run.get("underline"),
db.attrib["name"],
run.text
])输出:
>>> runs
[['1', None, None, None, None, '1', None, None, '1 off', 'row 1'],
['1', None, None, None, None, None, None, None, '1 off', 'Æ'],
['1', None, None, None, None, '2', None, None, '1 off', 'row 2'],
['3', None, None, None, None, None, None, None, '1 off', 'id2']]https://stackoverflow.com/questions/71156693
复制相似问题