如何使用Python搜索和替换XML文件中的文本?

2024-03-28 15:59:58 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在整个xml文件中搜索特定的文本模式,然后在Python 3.5中用新的文本模式替换每个出现的文本?

其他所有内容(格式、属性、注释等)都需要保留在原始xml文件中。

我在Windows(win32)上运行Python 3.5.1。

具体来说,我想用“THIS WORKED”替换每次出现的“FEATURE NAME”,用“12345”替换每次出现的“FEATURE NUMBER”。

我一直在尝试学习Python和xml.etree.ElementTree,但是没有弄清楚。我已经看过“在Python中搜索并替换.xml文件中的一行”、“在Python中搜索并替换文件中的一行”和“如何使用Python搜索并替换文件中的文本?”和其他现有的Q/A在这个网站上,但无法解决这个问题-我不是一个有经验的程序员,所以请让我知道,如果需要更多的输入。非常感谢您的帮助!!!

这是我在记事本中打开xml代码时它的样子的一个副本(除了我添加了空格来缩进每一行,并在将其粘贴到这个问题中时单击了某些行的return):

<description-topic>
    <access-info>
        <index-term-set>
            <index-term>
                <primary>FID FEATURE NUMBER</primary>
            </index-term>
            <index-term>
                <primary>FEATURE NAME</primary>
            </index-term>
            <index-term>
                <primary>Common features</primary>
                <secondary>FID FEATURE NUMBER</secondary>
            </index-term>
        </index-term-set>
    </access-info>
    <title>FEATURE NUMBER - FEATURE NAME</title>
    <block>
        <label>Platform</label>
        <comment>REVIEWERS: I guessed at the FEATURE NAME</comment>
        <para>
            This feature applies to the following platforms: FEATURE NAME<!--Check the values--></para>
    </block>
    <block branch="no">
        <label>Feature Benefits</label>
        <para>
            <comment>REVIEWERS: What do we put here? See template (link given in review email) for more information.</comment>
        </para>
    </block>
    <block branch="no">
        <label>Dependencies</label>
        <para/>
        <subblock>
            <label>Features</label>
            <comment>What FEATURE NAME do we put here?</comment>
        </subblock>
        <subblock>
            <label>Hardware</label>
            <comment>What FEATURE NAME do we put here?</comment>
            <para>This feature applies to the following: FEATURE NUMBER and text.</para><?Pub Caret -1?>
        </subblock>
        <subblock>
            <label>Dependencies outside the eNodeB</label>
            <comment>What FEATURE NAME do we put here?</comment>
        </subblock>
    </block>
    <block branch="no">
        <label>Impacts</label>
        <comment>REVIEWERS: What FEATURE NUMBER do we put here?</comment>
        <para>
            <comment/>
        </para>
    </block>
</description-topic>

下面是我要开始工作的最新代码:

from xml.etree import ElementTree as et
tree = et.parse('Atemplate2.xml')
tree.find('description-topic/access-info/index-term-set/index-term/primary/').text = '12345'
tree.write('Atemplate2.xml')

我得到以下错误: 回溯(最近一次呼叫时间): 文件“ajktest18.py”,第15行,in tree.find('description-topic/access-info/index-term-set/index-term/primary/')。文本='12345'

AttributeError:“NoneType”对象没有“text”属性

我更希望能够搜索和修改整个文件中的任何事件,但我不知道如何找到我正在搜索的文本的一个特定事件。

下面是我试图用来查找路径的代码:

import xml.etree.ElementTree as ET
tree = ET.parse('Atemplate.xml')
root = tree.getroot()

print(root.tag, root.attrib, root.text)

for child in root:
    print(child.tag, child.attrib, child.text)
for label in root.iter('label'):
    print(label.tag, label.attrib, label.text)
for title in root.iter('title'):
    print(title.attrib)

我还尝试了以下代码:

with open('Atemplate2.xml') as f:
    tree = ET.parse(f)
    root = tree.getroot()

for elem in root.getiterator():
    try:
        elem.text = elem.text.replace('FEATURE NAME', 'THIS WORKED')
        elem.text = elem.text.replace('FEATURE NUMBER', '12345')
    except AttributeError:
        pass

tree.write('output.xml')

但这会导致以下错误:

File "<pyshell#40>", line 2, in <module>
    tree = ET.parse(f)
File "C:\MyPath\Python35-32\lib\xml\etree\ElementTree.py", line 1182, in parse
    tree.parse(source, parser)
File "C:\ MyPath \Python35-32\lib\xml\etree\ElementTree.py", line 594, in parse
    self._root = parser._parse_whole(source)
File "C:\ MyPath \Python35-32\lib\encodings\cp1252.py", line 23, in decode
    return codecs.charmap_decode(input,self.errors,decoding_table)[0]

UnicodeDecodeError:“charmap”编解码器无法解码位置1119中的字节0x9d:字符映射到

# #

最后的更新-这是最后对我有用的代码(谢谢你,Jarad!):

import lxml.etree as ET
#using lxml instead of xml preserved the comments

#adding the encoding when the file is opened and written is needed to avoid a charmap error
with open('filename.xml', encoding="utf8") as f:
  tree = ET.parse(f)
  root = tree.getroot()


  for elem in root.getiterator():
    try:
      elem.text = elem.text.replace('FEATURE NAME', 'THIS WORKED')
      elem.text = elem.text.replace('FEATURE NUMBER', '123456')
    except AttributeError:
      pass

#tree.write('output.xml', encoding="utf8")
# Adding the xml_declaration and method helped keep the header info at the top of the file.
tree.write('output.xml', xml_declaration=True, method='xml', encoding="utf8")

Tags: thetextnameintreeindexparsecomment
1条回答
网友
1楼 · 发布于 2024-03-28 15:59:58

注意事项:

  • 我从未使用过xml.etree.ElementTree
  • 我从未使用过它,因为我从未发现自己在操纵XML
  • 我不知道这是不是比一个了解图书馆的人更好的方法
  • 评论者似乎倾向于评判你而不是帮助你

这是对this excellent answer的修改。问题是,您需要读入XML文件并对其进行解析。

import xml.etree.ElementTree as ET

with open('xmlfile.xml', encoding='latin-1') as f:
  tree = ET.parse(f)
  root = tree.getroot()

  for elem in root.getiterator():
    try:
      elem.text = elem.text.replace('FEATURE NAME', 'THIS WORKED')
      elem.text = elem.text.replace('FEATURE NUMBER', '123456')
    except AttributeError:
      pass

tree.write('output.xml', encoding='latin-1')

请注意,您可以将encoding参数更改为其他参数,例如:utf-8cp1252ISO-8859-1,等等,这取决于您的系统和文件。

相关问题 更多 >