解析XML fi时出现问题

2024-04-18 07:23:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经被困在这个问题上好几天了:

我有一个与此类似的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

如果有人能给我指出正确的方向,那就太好了。我还是个编程初学者,现在有点困了。我也很抱歉,如果格式不正确,这是我第一次张贴。你知道吗

谢谢!你知道吗


Tags: noyoutrueisemailaddressesxmlcontent
1条回答
网友
1楼 · 发布于 2024-04-18 07:23:26

我猜你是想在某个阶段打印你没有显示的地址名。它是一个节点列表,所以你可以尝试

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

(同样,当您应该使用地址时,您也在使用地址,反之亦然,但这不会导致问题更难阅读)

相关问题 更多 >