【问题标题】:Issue when parsing XML file解析 XML 文件时的问题
【发布时间】:2017-04-21 09:34:49
【问题描述】:

我已经被这个问题困扰了几天了:

我有一个与此类似的 XML 文件(包含 100 个条目)

<?xml version='1.0' encoding='us-ascii'?>
<content>
    <email a="1" b="0">somename@somedomain.com</email>
    <email a="0" b="1">otherdomain@somedomain.org</email>
</content>

我当前的代码正在尝试解析这个 xml 文件:

 from xml.dom import minidom
    xmldoc = minidom.parse("data.xml")
    content = xmldoc.getElementsByTagName("content")
    address = xmldoc.getElementsByTagName("email")
    for addresses in address:
       Allow = True
       Block = True
       addressName = xmldoc.getElementsByTagName("email")
       getB = addresses.attributes["b"]
       b = getB.value
       getA = addresses.attributes["a"]
       a= getA.value
    #setting allow and block list values
       if (a == "1"):
         Allow = True
         print("This is allowed.")
       elif (b == "1"):
         Block = True
         print("No, you cannot do that")

现在,我得到以下输出:

<DOM Element: addr at 0x3102850>
This is allowed.
<DOM Element: addr at 0x3102850>
No, you cannot do that

我预期/希望的结果是:

somename@somedomain.com
This is allowed.
otherdomain@somedomain
No, you cannot do that

如果有人能指出我正确的方向,那就太好了。我仍然是编程的初学者,现在有点卡住了。如果格式不正确也很抱歉,这是我第一次发帖。

谢谢!

【问题讨论】:

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


    【解决方案1】:

    我猜您正在尝试在某个未显示的阶段打印 addressName。它是一个 NodeList,所以你可以试试

    print (addressName[0].firstChild.nodeValue)
    

    但是你已经在地址中有节点,所以你可以

    print (addresses.firstChild.nodeValue)
    

    剥离它:

    from xml.dom import minidom
    xmldoc = minidom.parse("data.xml")
    address = xmldoc.getElementsByTagName("email")
    for addresses in address:
       Allow = True
       Block = True
       b = addresses.attributes["b"].value
       a = addresses.attributes["a"].value
       #setting allow and block list values
       print (addresses.firstChild.nodeValue)
       if (a == "1"):
         Allow = True
         print("This is allowed.")
       elif (b == "1"):
         Block = True
         print("No, you cannot do that")
    

    但您可能在不同的 XML 中有多个文本元素,因此您可能需要使用:

       print (" ".join(t.nodeValue for t in addresses.childNodes if t.nodeType == t.TEXT_NODE))
    

    (当你应该使用地址时,你正在使用地址,反之亦然,但它不会导致更难阅读的问题)

    【讨论】:

      猜你喜欢
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多