【发布时间】:2018-11-29 14:14:00
【问题描述】:
我制作了一个 python 脚本,需要在 XML 中包含一些参数。所以这里是 XML:
<ROOT>
<FOLDERTYPES>
<FOLDERTYPE_ID>
<NAME>FOURNISSEUR</NAME>
<ID>2</ID>
<SUBFOLDER>
<NAME>Administratif</NAME>
<ID>4</ID>
</SUBFOLDER>
<SUBFOLDER>
<NAME>Commandes</NAME>
<ID>5</ID>
</SUBFOLDER>
<SUBFOLDER>
<NAME>Factures</NAME>
<ID>6</ID>
</SUBFOLDER>
</FOLDERTYPE_ID>
<FOLDERTYPE_ID>
<NAME>CLIENT</NAME>
<ID>3</ID>
<SUBFOLDER>
<NAME>Administratif</NAME>
<ID>4</ID>
</SUBFOLDER>
<SUBFOLDER>
<NAME>Commandes</NAME>
<ID>5</ID>
</SUBFOLDER>
<SUBFOLDER>
<NAME>Factures</NAME>
<ID>6</ID>
</SUBFOLDER>
<SUBFOLDER>
<NAME>Logistique</NAME>
<ID>7</ID>
</SUBFOLDER>
</FOLDERTYPE_ID>
</FOLDERTYPES>
目前,我只能获得如下的“名称”和“ID”:
{'FOURNISSEUR': {'id': '2'}, 'CLIENT': {'id': '3'}}
但我需要在这样的字典中拥有所有子文件夹:
{'FOURNISSEUR': {'id': '2', 'subfolders' : {'Administratif':'4','Commandes':'5','Factures':'6'}}, 'CLIENT': {'id': '3', 'subfolders' : {'Administratif':'4','Commandes':'5','Factures':'6','Logistique':'7'}}
这是我现在拥有的一段代码:
def getFolderTypeArray(fileName):
result = {}
with open(fileName, 'rb') as config_file:
content = config_file.read()
config = BeautifulSoup(content, "lxml")
folderTypesId = config.find_all('foldertype_id')
for folderType in folderTypesId:
label = folderType.find('name').string
folderTypeId = folderType.find('id').string
result[label] = {'id' : folderTypeId}
【问题讨论】:
-
它们在 python 中被称为字典或
dicts,而不是关联数组。你可能需要一个 xml 解析器:docs.python.org/3/library/xml.etree.elementtree.html -
好吧,你在哪里制作子文件夹键?
-
@cricket_007 现在我没有为子文件夹编写任何代码。我只是做了一些尝试,但没有成功,因为我不知道如何实现这一点
-
result['subfolders'] = some_dictionary在循环之后。在循环中构建内部字典...您已经在构建字典。result[label]和{'id' : folderTypeId}
标签: python xml beautifulsoup