Python在不知道标记的情况下在XML文件中搜索和替换文本(标记的值)

时间:2014-07-21 14:43:06

标签: python xml parsing search replace

我是Python的新手,我正在尝试使用XML文件。我知道如何解析和搜索知道结构的信息,但我不知道如何在不知道附加该值的标记的情况下搜索值。

例如:

<bookstore>
  <book category="COOKING">
  <title lang="en">Everyday Italian</title>
  <author>TRUE</author>
  <year>2005</year>
  <price>30.00</price>
</book>
  <book category="CHILDREN">
  <title lang="en">Harry Potter</title>
  <author>J K. Rowling</author>
  <year>2005</year>
  <price>29.99</price>
</book>
<book category="WEB">
  <title lang="en">Learning XML</title>
  <author>Erik T. Ray</author>
  <year>TRUE</year>
  <price>39.95</price>
  </book>
<adventure>
  <title lang="en">Learning XML</title>
  <author>Erik T. Ray</author>
  <year>TRUE</year>
  <price>TRUE</price>
</adventure>
</bookstore>

在这个例子中,我想找到所有“TRUE”值并将此值替换为“OK”。你会怎么做?

谢谢

3 个答案:

答案 0 :(得分:1)

这是使用标准库中的xml.etree.ElementTree的选项:

import xml.etree.ElementTree as ET

data = """xml here"""

tree = ET.fromstring(data)     
for element in tree.getiterator():
    if element.text == 'TRUE': 
        element.text = 'OK'    

print ET.tostring(tree)   

打印:

<bookstore>
  <book category="COOKING">
  <title lang="en">Everyday Italian</title>
  <author>OK</author>
  <year>2005</year>
  <price>30.00</price>
</book>
  <book category="CHILDREN">
  <title lang="en">Harry Potter</title>
  <author>J K. Rowling</author>
  <year>2005</year>
  <price>29.99</price>
</book>
<book category="WEB">
  <title lang="en">Learning XML</title>
  <author>Erik T. Ray</author>
  <year>OK</year>
  <price>39.95</price>
  </book>
<adventure>
  <title lang="en">Learning XML</title>
  <author>Erik T. Ray</author>
  <year>OK</year>
  <price>OK</price>
</adventure>
</bookstore>

答案 1 :(得分:0)

如果单词TRUE仅存在于标签之间,则应该能够使用简单的字符串替换

my_xml = """
<bookstore>
  <book category="COOKING">
  <title lang="en">Everyday Italian</title>
  <author>TRUE</author>
  <year>2005</year>
  <price>30.00</price>
</book>
  <book category="CHILDREN">
  <title lang="en">Harry Potter</title>
  <author>J K. Rowling</author>
  <year>2005</year>
  <price>29.99</price>
</book>
<book category="WEB">
  <title lang="en">Learning XML</title>
  <author>Erik T. Ray</author>
  <year>TRUE</year>
  <price>39.95</price>
  </book>
</bookstore>
"""
>>> my_xml.replace(">TRUE<",">OK<")
'\n<bookstore>\n  <book category="COOKING">\n  <title lang="en">Everyday Italian</title>\n  <author>OK</author>\n  <year>2005</year>\n  <price>30.00</price>\n</book>\n  <book category="CHILDREN">\n  <title lang="en">Harry Potter</title>\n  <author>J K. Rowling</author>\n  <year>2005</year>\n  <price>29.99</price>\n</book>\n<book category="WEB">\n  <title lang="en">Learning XML</title>\n  <author>Erik T. Ray</author>\n  <year>OK</year>\n  <price>39.95</price>\n  </book>\n</bookstore>\n'
>>> 

绝对不像使用xml lib那样健壮,但应该完成工作。

答案 2 :(得分:0)

这里我做了什么,并允许我在我的xml文件中找到所有值。

for node in root.iter():
        if (node.text != None):
            node.text = search_in_dictonary_foot(">"+node.text+"<")