我正在尝试将 xml 的小结构注入到现有 xml 文件中的特定位置:
<not>
<elt>
<isVal>Y</isVal>
</elt>
</not>
我的代码如下所示:
import lxml.etree as ElementTree;
tree = ElementTree.ElementTree()
tree.parse(file_path)
root = tree.getroot();
ruleElement = tree.find('.//rule');
for child_n in ruleElement:
if (child_n.tag == 'and'):
print "Found rule - and"
ruleElement.insert(0, tree.XML("<not><elt><isVal>Y</isVal></elt></not>"))
我收到以下错误:AttributeError:“lxml.etree._ElementTree”对象没有属性“XML”
我也尝试过:
for child_n in ruleElement:
if (child_n.tag == 'and'):
print "Found rule - and"
child_n.Element(child_n, 'test_insert').text = 'test'
child_n.insert(1, item[0])
这给出:AttributeError:“lxml.etree._ElementTree”对象没有属性“Element”
尝试将其作为子元素,得到相同的错误消息:AttributeError:“lxml.etree._Element”对象没有属性“SubElement”
我从其他类似的问题中得到了如何做到这一点的想法,但它似乎不想接受 Element、SubElement 或 XML 作为可接受的属性。我究竟做错了什么?
我使用的是 Python 2.6,无法升级。
您需要使用创建“元素”lxml.etree.SubElement
:
import lxml.etree
xml = lxml.etree.parse('xyz.xml')
root = xml.getroot()
nt = lxml.etree.SubElement(root, 'not') # add to the XML root!
elt = lxml.etree.SubElement(nt, 'elt')
isVal = lxml.etree.SubElement(elt, 'isVal')
isVal.text = 'Y'
with open("xyz2.xml", 'wb') as f:
f.write(lxml.etree.tostring(root, xml_declaration=True, encoding="utf-8"))
print(open("xyz2.xml", 'r').read())
Output:
<?xml version='1.0' encoding='utf-8'?>
<note>
<to>abc</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Party</body>
<not><elt><isVal>Y</isVal></elt></not></note>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)