AttributeError插入Python中的lxml

AttributeError插入Python中的lxml

本文介绍了AttributeError插入Python中的lxml树中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一小段xml结构注入到已经存在的xml文件中的特定位置:

I'm trying to inject a small structure of xml into a specific location in an already existing xml file:

<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"

尝试将其作为SubElement,得到相同的错误消息: AttributeError:'lxml.etree._Element'对象没有属性'SubElement'

Tried it as SubElement, got the same error message:AttributeError: 'lxml.etree._Element' object has no attribute 'SubElement'

我从其他类似的问题中得到了有关如何执行此操作的想法,但似乎只是不想接受Element,SubElement或XML作为可接受的属性.我在做什么错了?

I got the ideas on how to do it from other similar questions but it just doesn't seem to want to accept Element, SubElement or XML as acceptable attributes. What am I doing wrong?

我正在使用Python 2.6,无法升级.

I'm using Python 2.6, upgrading isn't an option.

推荐答案

您需要使用 lxml.etree.SubElement 创建

You need to create 'elements' using 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())

输出:

<?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>

这篇关于AttributeError插入Python中的lxml树中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 07:21