我需要将xml文件中名为approved-by
的属性的值从“no”更改为“yes”。这是我的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>
我试过两种方式,两种方式都失败了。我的第一种方式是
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)
通过这种方式,我收到一条错误消息AttributeError: 'NoneType' object has no attribute 'set'
。
所以我尝试了另一种方式。
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"
我没有收到任何错误,也没有设置属性。我很困惑,并且无法找到这个脚本的错误。
答案 0 :(得分:6)
由于您提供的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)
打印:
<body>
<approved-by approved="yes">
<name>AB</name>
<signature>errrrrn</signature>
</approved-by>
</body>
所以,你尝试过的第一种方式。希望有所帮助。