【问题标题】:How to parse and modify xml data using python lxml如何使用python lxml解析和修改xml数据
【发布时间】:2019-06-15 10:43:21
【问题描述】:

我需要通过解析 xml 文件来使用 lxml(作者和描述)修改 XML 标记值。下面是我正在使用的输入文件和我需要的输出文件。以下是我正在使用的代码:

输入xml文件:

<Summary>  
<Author>ABC</Author>  
<Description>ABC DATA</Description>  
<Function>24</Function>  
</Summary>

所需的输出文件:

<Summary>  
<Author>DEF</Author>  
<Description>DEF DATA</Description>  
<Function>24</Function>  
</Summary> 

from lxml import etree  
root = etree.parse(r"C:\Users\input\input.xml")  
    for elem in root.xpath('.//Author'): 
    elem.text = "DEF"  
    root.write("output.xml", pretty_print=True,xml_declaration=True,encoding="UTF-8")

【问题讨论】:

  • 你当前的代码有什么问题?

标签: python xml python-3.6 lxml


【解决方案1】:

这应该可以工作

import xml.etree.ElementTree as ET

xml = '''<root>
    <Summary>  
        <Author>ABC</Author>  
        <Description>ABC DATA</Description>  
        <Function>24</Function>  
    </Summary>
    <Summary>  
        <Author>ABC</Author>  
        <Description>ABC DATA</Description>  
        <Function>24</Function>  
    </Summary>
</root>'''

tree = ET.fromstring(xml)
for author in tree.findall('.//Summary/Author'):
    author.text = 'new author value goes here'
for desc in tree.findall('.//Summary/Description'):
    desc.text = 'new desc value goes here'

ET.dump(tree)
# call the line below if you need to save to a file
# tree.write(open('new_file.xml', 'w'))

输出

<root>
    <Summary>  
        <Author>new author value goes here</Author>  
        <Description>new desc value goes here</Description>  
        <Function>24</Function>  
    </Summary>
    <Summary>  
        <Author>new author value goes here</Author>  
        <Description>new desc value goes here</Description>  
        <Function>24</Function>  
    </Summary>
</root>

【讨论】:

  • tree = ET.parse(r"C:\Users\input.mxl") root = tree.getroot() for author in root.findall('./Summary/Author'): author .text = "DEF" tree.write('output.mxl', xml_declaration=True, encoding="UTF-8")
  • 我试过上面的代码。但是控制没有进入 for 循环
  • @ishkk467 您是否复制并粘贴了代码并尝试运行它?请参阅repl.it/repls/TomatoNutritiousSet 以获取相同代码的在线(运行)版本。
  • 是的,遇到同样的问题..Control无法进入for循环。不知道我哪里做错了。
  • 点击我之前评论中的链接。它指向一个包含代码的在线 python 编辑器。点击“运行”并查看它的实际效果。让我知道它是否适合您。
【解决方案2】:

如果您只想将每次出现的“ABC”替换为“DEF”,否则将文本保持原样,应该这样做:

dat = [your input above]

nodes = ['Author','Description']
for node in nodes:
    for elem in root.xpath(f'.//{node}'): 
        elem.text = elem.text.replace("ABC","DEF")  

输出是你想要的输出。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多