Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Python从xml文件中获取子元素值_Python_Xml_Elementtree - Fatal编程技术网

使用Python从xml文件中获取子元素值

使用Python从xml文件中获取子元素值,python,xml,elementtree,Python,Xml,Elementtree,我需要使用Python从.xml文件中提取/修改一个子元素。为此,我使用了xml.etree.ElementTree,但我没有从代码中获得所需的输出。我需要从.xml文件中提取“deployment”(在本例中为xyz1000_Test_v1)下的元素“name”: <?xml version="1.0" encoding="utf-8"?> <esc xmlns="http://www.test.com/esc/esc"> <tenants>

我需要使用Python从.xml文件中提取/修改一个子元素。为此,我使用了xml.etree.ElementTree,但我没有从代码中获得所需的输出。我需要从.xml文件中提取“deployment”(在本例中为xyz1000_Test_v1)下的元素“name”:

<?xml version="1.0" encoding="utf-8"?>
<esc
    xmlns="http://www.test.com/esc/esc">
    <tenants>
        <tenant>
            <name>esc</name>
            <deployments>
                <deployment>
                    <name>xyz1000_Test_v1</name>
                    <networks>
                        <network>
                            <name>tenant_1</name>
                            <admin_state>true</admin_state>
                            <subnet>
                                <name>tenant_1_sub</name>
                                <ipversion>ipv4</ipversion>
                                **<address>10.25.0.0</address>**
                            </subnet>
                        </network>
                        <network> .....
然而,在代码中,我得到了“部署”、“网络”和“子网”下的元素值。如何访问特定元素?提前谢谢

更新:

试图从“network”元素中获取“name”,我有以下代码。不幸的是,它没有给我预期的答案:

for network in root.findall('{http://www.test.com/esc/esc}network'):
    name = network.find('name').text
    print(name)

文档中的所有元素都绑定到同一名称空间,并且
网络
元素不是根的直接子元素

使用
findall()
,使用以下命令:

for network in root.findall('.//{http://www.test.com/esc/esc}network'):
    name = network.find('{http://www.test.com/esc/esc}name')
或者使用
iter()


谢谢我选择了iter()。但是当我试图修改它的值时,我得到了以下错误:“AttributeError:‘NoneType’对象没有属性‘text’”。要更改名称,我只需在“for”循环中使用:name.text='newname'。然而,当我尝试使用元素“deployment”时,它是有效的。我怎么才能更正呢?我想您至少有一个
网络
元素没有
名称
子元素。您可以通过在
name.text='newname'
之前添加
(如果name不是None:
)来检查这一点。
for network in root.findall('.//{http://www.test.com/esc/esc}network'):
    name = network.find('{http://www.test.com/esc/esc}name')
for network in root.iter('{http://www.test.com/esc/esc}network'):
    name = network.find('{http://www.test.com/esc/esc}name')
    if name is not None:  # Avoid "'NoneType' object has no attribute 'text'"
        name.text= 'new name'