【问题标题】:Parsing XML using minidom in Python在 Python 中使用 minidom 解析 XML
【发布时间】:2018-10-23 23:58:51
【问题描述】:

我是 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:   12345-67890
Visio Professional 2008:   23456-78901
Visio Professional 2012:   34567-89012
Visio Professional 2016:   45678-90123

我正在尝试获取产品名称,并在其前面获取相应的产品密钥。

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

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();

【问题讨论】:

    标签: python python-3.x xml-parsing minidom


    【解决方案1】:

    大部分工作都是您自己完成的。恭喜。

    有很多方法可以实现你的最终目标,其中一种是:现在你得到了nameskeys列表,你可以将它们组合起来构造一个字典,然后遍历字典得到得到你正在寻找的合适的输出。

    所以你的程序可能如下所示:

    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
    

    【讨论】:

    • 谢谢比拉尔。它就像一个魅力..祝你有美好的一天! :)
    猜你喜欢
    • 2017-09-22
    • 1970-01-01
    • 1970-01-01
    • 2015-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多