如何在XML文件中获取值?蟒蛇

时间:2015-12-30 14:12:50

标签: python xml python-2.7

我可以找到元素,但我想获得标签的值 这是我的xml文件。

<?xml version="1.0" encoding="UTF-8"?><BusinessTransactions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Controller="http://10.43.11.143:8090/controller/rest" GenerationTime="2015-12-30T09:47:46.817698-03:00" xsi:noNamespaceSchemaLocation="bt_metrics.xsd"> 
 <BusinessTransaction>
<ApplicationName>Portales</ApplicationName>
<BusinessTransactionName>APP</BusinessTransactionName>
<AverageResponseTime>142</AverageResponseTime>      
<CallsPerMinute>169</CallsPerMinute>
<ErrorsPerMinute>15</ErrorsPerMinute>

和我的代码

from xml.dom.minidom import parse, parseString
from xml.dom import minidom
dom = parse("data.xml")
for node in dom.getElementsByTagName('CallsPerMinute'): 
print node.toxml()

1 个答案:

答案 0 :(得分:3)

您需要使用firstChild.nodeValue才能获取节点的值:

from xml.dom.minidom import parse

dom = parse("data.xml")
for node in dom.getElementsByTagName('CallsPerMinute'):
    print(node.firstChild.nodeValue)

此外,您的xml需要关闭您的代码:

<?xml version="1.0" encoding="UTF-8"?>
<BusinessTransactions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                      Controller="http://10.43.11.143:8090/controller/rest"
                      GenerationTime="2015-12-30T09:47:46.817698-03:00" xsi:noNamespaceSchemaLocation="bt_metrics.xsd">
    <BusinessTransaction>
        <ApplicationName>Portales</ApplicationName>
        <BusinessTransactionName>APP</BusinessTransactionName>
        <AverageResponseTime>142</AverageResponseTime>
        <CallsPerMinute>169</CallsPerMinute>
        <ErrorsPerMinute>15</ErrorsPerMinute>
    </BusinessTransaction>
</BusinessTransactions>