Python 使用 ElementTree 在 XML 文件中设置属性值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17922056/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Setting an attribute value in XML file using ElementTree
提问by Shahul Hameed
I need to change the value of an attribute named approved-by
in an xml file from 'no' to 'yes'. Here is my xml file:
我需要将approved-by
xml 文件中命名的属性的值从“否”更改为“是”。这是我的 xml 文件:
<?xml version="1.0" encoding="UTF-8" ?>
<!--Arbortext, Inc., 1988-2008, v.4002-->
<!DOCTYPE doc PUBLIC "-//MYCOMPANY//DTD XSEIF 1/FAD 110 05 R5//EN"
"XSEIF_R5.dtd">
<doc version="XSEIF R5" xmlns="urn:x-mycompany:r2:reg-doc:1551-fad.110.05:en:*">
<meta-data>
<?Pub Dtl?>
<confidentiality class="mycompany-internal" />
<doc-name>INSTRUCTIONS</doc-name>
<doc-id>
<doc-no type="registration">1/1531-CRA 119 1364/2</doc-no>
<language code="en" />
<rev>PA1</rev>
<date>
<y>2013</y>
<m>03</m>
<d>12</d>
</date>
</doc-id>
<company-id>
<business-unit></business-unit>
<company-name></company-name>
<company-symbol logotype="X"></company-symbol>
</company-id>
<title>SIM Software Installation Guide</title>
<drafted-by>
<person>
<name>Shahul Hameed</name>
<signature>epeeham</signature>
</person>
</drafted-by>
<approved-by approved="no">
<person>
<name>AB</name>
<signature>errrrrn</signature>
</approved-by>
I tried in two ways, and failed in both. My first way is
我尝试了两种方法,都失败了。我的第一种方法是
import xml.etree.ElementTree as ET
from xml.etree.ElementTree import Element
root = ET.parse('Path/1_1531-CRA 119 1364_2.xml')
sh = root.find('approved-by')
sh.set('approved', 'yes')
print etree.tostring(root)
In this way, I got an error message saying AttributeError: 'NoneType' object has no attribute 'set'
.
这样,我收到一条错误消息,说AttributeError: 'NoneType' object has no attribute 'set'
.
So I tried another way.
所以我尝试了另一种方式。
import xml.etree.ElementTree as ET
from xml.etree.ElementTree import Element
root = ET.parse('C:/Path/1_1531-CRA 119 1364_2.xml')
elem = Element("approved-by")
elem.attrib["approved"] = "yes"
I didn't get any error, also it didn't set the attribute either. I am confused, and not able to find whats wrong with this script.
我没有收到任何错误,也没有设置属性。我很困惑,无法找到这个脚本有什么问题。
回答by alecxe
Since the xml you've provided is not valid, here's an example:
由于您提供的 xml 无效,下面是一个示例:
import xml.etree.ElementTree as ET
xml = """<?xml version="1.0" encoding="UTF-8"?>
<body>
<approved-by approved="no">
<name>AB</name>
<signature>errrrrn</signature>
</approved-by>
</body>
"""
tree = ET.fromstring(xml)
sh = tree.find('approved-by')
sh.set('approved', 'yes')
print ET.tostring(tree)
prints:
印刷:
<body>
<approved-by approved="yes">
<name>AB</name>
<signature>errrrrn</signature>
</approved-by>
</body>
So, the first way you've tried works. Hope that helps.
因此,您尝试的第一种方法有效。希望有帮助。