当前位置: 代码迷 >> python >> 在xml文件中解析后如何修改字符串?
  详细解决方案

在xml文件中解析后如何修改字符串?

热度:119   发布时间:2023-06-13 13:53:52.0

我是 python 新手,我想学习 python 语言。 在 xml 文件中解析后,我无法找到修改字符串的解决方案。

这是示例 xml 文件:

<Celeb>
  <artist>
    <name>Sammy Jellin</name>
    <age>27</age>
    <bday>01/22/1990</bday>
    <country>English</country>
    <sign>Virgo</sign>
  </artist>
</Celeb>

这是代码:

def edit_f():
# Get the 3rd attribute 
    root = ET.parse('test_file/test_file.xml').getroot()
    subroot = root.getchildren()
    listchild = subroot.getchildren()[2].text
    print(listchild)

# Update the string for the <bday>
    replaceStr = listchild.replace('01/22/1990', '01/22/1992')

def main():
    edit_f()

结尾

如何更新日期? 我也尝试使用 datetime() 但不好。

感谢您的帮助。

我为您的示例添加了带有注释的工作代码。

def edit_f():
    tree = ET.parse('test_file/test_file.xml')
    root = tree.getroot()
    bdays = root.findall('.//artist/bday')  # note: multiple elements
    bday = bdays[0]  # assuming there is only one artist/bday element
    bday.text = '01/22/1992'  # or ever any string you need
    tree.write('test_file/test_file.xml')  # with edited bday

你在这里不需要datetime ,只需将你想要的任何字符串分配给bday.text

NB tree.write()将重写您的源文件,您无法撤消。 将输出写入另一个文件要安全得多。

  相关解决方案