我有一个xml文件,结构如下:
<main_tag>
<first>
<tag1>val1</tag1>
<conf>
<tag2>val2</tag2>
<tag3>val3</tag3>
<tag4>val4</tag4>
</conf>
</first>
<second>
<tag1>val2</tag1>
<conf>
<tag2>val6</tag2>
<tag3>val7</tag3>
<tag4>val8</tag4>
</conf>
</second>
</main_tag>
我必须更改tag2的值。可能的值存储在dict中:
{tag2values:[newvalue1, newvalue2]}
如果tag1的值是val1,那么我们将tag2值更改为newvalue1。如果tag1值为val2,那么我们将tag2值更改为newvalue2。
所以问题是:有没有办法在lxml中找到与其父值相匹配的元素? 或者通过它的父邻居值找到一个元素?
答案 0 :(得分:4)
.xpath
method让你找到XPath 1.0表达式的标签:
>>> from lxml import etree
>>> from cStringIO import StringIO
>>> tag2values = ['newvalue1', 'newvalue2']
>>> example = StringIO("""\
... <main_tag>
... <first>
... <tag1>val1</tag1>
... <conf>
... <tag2>val2</tag2>
... <tag3>val3</tag3>
... <tag4>val4</tag4>
... </conf>
... </first>
... <second>
... <tag1>val2</tag1>
... <conf>
... <tag2>val6</tag2>
... <tag3>val7</tag3>
... <tag4>val8</tag4>
... </conf>
... </second>
... </main_tag>
... """)
>>> tree = etree.parse(example)
>>> value1selector = '*/conf/tag2[../../tag1/text() = "val1"]'
>>> value2selector = '*/conf/tag2[../../tag1/text() = "val2"]'
>>> for elem in tree.xpath(value1selector):
... elem.text = tag2values[0]
...
>>> for elem in tree.xpath(value2selector):
... elem.text = tag2values[1]
...
>>> print(etree.tostring(tree, pretty_print=True))
<main_tag>
<first>
<tag1>val1</tag1>
<conf>
<tag2>newvalue1</tag2>
<tag3>val3</tag3>
<tag4>val4</tag4>
</conf>
</first>
<second>
<tag1>val2</tag1>
<conf>
<tag2>newvalue2</tag2>
<tag3>val7</tag3>
<tag4>val8</tag4>
</conf>
</second>
</main_tag>
在上面的示例中,value1selector
中的XPath表达式为您提供了所有tag2
个conf
个子元素,其中包含带有文本{{1}的同级tag1
标记},作为ElementTree val1
实例,因此替换其文本内容变得微不足道。