这是使用 LXML 进行解析的最佳方法吗?
Is this the best approach to parsing with LXML?
我是 LXML 的新手,一般会解析 XML 个文档。我已经编写了一小段代码,似乎也可以完成我需要它做的事情,但感觉我把它复杂化了。有什么办法可以简化这个吗?
METHOD:
def importFromXML(self, filename):
tree = etree.parse(filename)
for child in tree.getroot():
if child.tag != 'SLOT':
print('Tag:', child.tag, ', Text', child.text)
elif child.tag == 'SLOT':
for slot, index in child.items():
for attribute in child:
print('Slot Number =', index, ', Tag:', attribute.tag, ', Value:', attribute.text)
XML:
<?xml version="1.0" encoding="UTF-8"?>
<Item>
<ActiveState>drop</ActiveState>
<Location>Left Wrist</Location>
<Realm>All</Realm>
<ItemName>Band of the Dream Conqueror</ItemName>
<ItemQuality>100</ItemQuality>
<Equipped>1</Equipped>
<Level>50</Level>
<TYPE>Wrist</TYPE>
<SOURCE>Drop</SOURCE>
<DBSOURCE>kscraft</DBSOURCE>
<SLOT Number="0">
<Type>Resist</Type>
<Effect>Crush</Effect>
<Amount>6</Amount>
</SLOT>
<SLOT Number="1">
<Type>Resist</Type>
<Effect>Thrust</Effect>
<Amount>6</Amount>
</SLOT>
<SLOT Number="2">
<Type>Resist</Type>
<Effect>Slash</Effect>
<Amount>6</Amount>
</SLOT>
</Item>
我只是想确保我做的是对的。我正在使用 Python 3.x
我认为您的解析没有什么可批评的。特别是,它的可读性很强,也很容易理解。但是,我建议对 if
语句进行微调。
- 以这种方式编写它避免了使用
not
,并且 not
增加了一个额外的障碍来理解代码,就像在自然语言中一样。
- 我舍弃了
elif
换成了普通的 else
。
if child.tag == 'SLOT':
for slot, index in child.items():
for attribute in child:
print('Slot Number =', index, ', Tag:', attribute.tag, ', Value:', attribute.text)
else:
print('Tag:', child.tag, ', Text', child.text)
我是 LXML 的新手,一般会解析 XML 个文档。我已经编写了一小段代码,似乎也可以完成我需要它做的事情,但感觉我把它复杂化了。有什么办法可以简化这个吗?
METHOD:
def importFromXML(self, filename):
tree = etree.parse(filename)
for child in tree.getroot():
if child.tag != 'SLOT':
print('Tag:', child.tag, ', Text', child.text)
elif child.tag == 'SLOT':
for slot, index in child.items():
for attribute in child:
print('Slot Number =', index, ', Tag:', attribute.tag, ', Value:', attribute.text)
XML:
<?xml version="1.0" encoding="UTF-8"?>
<Item>
<ActiveState>drop</ActiveState>
<Location>Left Wrist</Location>
<Realm>All</Realm>
<ItemName>Band of the Dream Conqueror</ItemName>
<ItemQuality>100</ItemQuality>
<Equipped>1</Equipped>
<Level>50</Level>
<TYPE>Wrist</TYPE>
<SOURCE>Drop</SOURCE>
<DBSOURCE>kscraft</DBSOURCE>
<SLOT Number="0">
<Type>Resist</Type>
<Effect>Crush</Effect>
<Amount>6</Amount>
</SLOT>
<SLOT Number="1">
<Type>Resist</Type>
<Effect>Thrust</Effect>
<Amount>6</Amount>
</SLOT>
<SLOT Number="2">
<Type>Resist</Type>
<Effect>Slash</Effect>
<Amount>6</Amount>
</SLOT>
</Item>
我只是想确保我做的是对的。我正在使用 Python 3.x
我认为您的解析没有什么可批评的。特别是,它的可读性很强,也很容易理解。但是,我建议对 if
语句进行微调。
- 以这种方式编写它避免了使用
not
,并且not
增加了一个额外的障碍来理解代码,就像在自然语言中一样。 - 我舍弃了
elif
换成了普通的else
。
if child.tag == 'SLOT':
for slot, index in child.items():
for attribute in child:
print('Slot Number =', index, ', Tag:', attribute.tag, ', Value:', attribute.text)
else:
print('Tag:', child.tag, ', Text', child.text)