在Python中使用minidom解析XML

在Python中使用minidom解析XML,python,python-3.x,xml-parsing,minidom,Python,Python 3.x,Xml Parsing,Minidom,我是Python新手,需要专家对我的一个项目提出一些建议 我有一个需要解析然后排序的xml文件。 下面是xml文件的示例 <Product_Key Name="Visio Professional 2002" KeyRetrievalNote=""> <Key ID=“XXX” Type="Static Activation Key">12345-67890</Key> </Product_Key> <Product_Key Na

我是Python新手,需要专家对我的一个项目提出一些建议

我有一个需要解析然后排序的xml文件。 下面是xml文件的示例

<Product_Key Name="Visio Professional 2002" KeyRetrievalNote="">
    <Key ID=“XXX” Type="Static Activation Key">12345-67890</Key>
</Product_Key>


<Product_Key Name="Visio Professional 2008" KeyRetrievalNote="">
    <Key ID=“XXX” Type="Static Activation Key">23456-78901</Key>
</Product_Key>


<Product_Key Name="Visio Professional 2012" KeyRetrievalNote="">
    <Key ID=“XXX” Type="Static Activation Key">34567-89012</Key>
</Product_Key>


<Product_Key Name="Visio Professional 2016” KeyRetrievalNote="">
    <Key ID=“XXX” Type="Static Activation Key">45678-90123</Key>
</Product_Key>
我正在尝试获取产品的名称以及前面相应的产品密钥

我可以得到如下的输出,但这不是我要找的

Visio Professional 2002
Visio Professional 2008
Visio Professional 2012
Visio Professional 2016 
12345-67890
23456-78901
34567-89012
45678-90123
下面是我使用的代码片段

import xml.dom.minidom

def main():
  doc = xml.dom.minidom.parse("keysexport.xml")
  names = doc.getElementsByTagName("Product_Key")
  keys = doc.getElementsByTagName("Key")

  for name in names:
    print(name.getAttribute("Name"))

  for key in keys:
    print(key.firstChild.nodeValue)

if __name__ == "__main__":
  main();

大部分工作你都是自己做的。祝贺你

实现最终目标的方法有很多,其中之一是:现在您已经获得了名称和键列表,您可以将它们组合起来构建一个字典,然后在字典上迭代以获得您想要的合适的输出

Visio Professional 2002
Visio Professional 2008
Visio Professional 2012
Visio Professional 2016 
12345-67890
23456-78901
34567-89012
45678-90123
因此,您的程序可以如下所示:

import xml.dom.minidom

def main():
  doc = xml.dom.minidom.parse("keysexport.xml")
  names = doc.getElementsByTagName("Product_Key")
  keys = doc.getElementsByTagName("Key")
  #Use the previous lists to create a dictionary
  products = dict(zip(names, keys)) 
  #Loop over the dictionary of products and display the couple key: value
  for product_key, product_value in products.items():
      print('{}:  {}'.format(product_key.getAttribute('Name'), product_value.firstChild.nodeValue))


if __name__ == "__main__":
  main()
演示:


谢谢比拉尔。它很有魅力。。祝你今天愉快
>>> names = xmldoc.getElementsByTagName("Product_Key")
>>> keys = xmldoc.getElementsByTagName("Key")
>>> products = dict(zip(names, keys))
>>> for product_key, product_value in products.items():
...     print('{}:  {}'.format(product_key.getAttribute('Name'), product_value.firstChild.nodeValue))
... 
Visio Professional 2002:  12345-67890
Visio Professional 2008:  23456-78901
Visio Professional 2012:  34567-89012
Visio Professional 2016:  45678-90123