• 修改xml文件


    一、前言

    本节是修改xml;同样方法也可修改arxml文件;主要使用LET.Element创建节点;

    二、知识点

     1、专门用于格式化处理xml文件使其具有层级分明的缩进函数

    #专门用于格式化处理xml文件使其具有层级分明的缩进

    def indent( elem, level=0):

        i = "\n" + level * "  "

        if len(elem):

            if not elem.text or not elem.text.strip():

                elem.text = i + "  "

            if not elem.tail or not elem.tail.strip():

                elem.tail = i

            for elem in elem:

                indent(elem, level + 1)

            if not elem.tail or not elem.tail.strip():

                elem.tail = i

        else:

            if level and (not elem.tail or not elem.tail.strip()):

                elem.tail = i

    2、修改XML文件

    #举例1:添加节点'country'

    import lxml.etree as LET

    tree = LET.parse('country_data.xml')

    root = tree.getroot()

    """

    country_ref = LET.Element("neighbor")

    country_ref.attrib['name'] = 'china'

    country =root.findall('country')

    print(country)

    country[0].append(country_ref)

    indent(root)

    tree.write("d:/myself/write_arxml/country_data.xml", xml_declaration=True, encoding='utf-8')

    """

    #alt+shift+A  整段注销

    3、修改节点rank文本值,添加属性

    #举例2:修改节点rank文本值,添加属性

    """

    for rank in root.iter('rank'):

        new_rank = int(rank.text) + 1

        rank.text = str(new_rank)

        rank.set('updated', 'yes')

    tree.write('output.xml')

     """

    4、删除节点

    #举例3 删除节点

    """

    for country in root.findall('country'):

        # using root.findall() to avoid removal during traversal

        rank = int(country.find('rank').text)

        if rank > 50:

            root.remove(country)

    tree.write('output.xml')

     """

    5、 构建 XML 文档

    #知识点4:构建 XML 文档¶

    """ a = LET.Element('a')

    b = LET.SubElement(a, 'b')

    c = LET.SubElement(a, 'c')

    d = LET.SubElement(c, 'd')

    LET.dump(a) #Writes an element tree or element structure to sys.stdout.

     """


    三、实例 代码

    1. import lxml.etree as LET
    2. #专门用于格式化处理xml文件使其具有层级分明的缩进
    3. def indent( elem, level=0):
    4. i = "\n" + level * " "
    5. if len(elem):
    6. if not elem.text or not elem.text.strip():
    7. elem.text = i + " "
    8. if not elem.tail or not elem.tail.strip():
    9. elem.tail = i
    10. for elem in elem:
    11. indent(elem, level + 1)
    12. if not elem.tail or not elem.tail.strip():
    13. elem.tail = i
    14. else:
    15. if level and (not elem.tail or not elem.tail.strip()):
    16. elem.tail = i
    17. #alt+shift+A 整段注销
    18. #可以通过从文件中读取来导入此数据:
    19. tree = LET.parse('country_data.xml')
    20. root = tree.getroot()
    21. #可以迭代的子节点
    22. """ for child in root:
    23. print(child.tag, child.attrib) """
    24. #子级是可以嵌套的,我们可以通过索引访问特定的子级节点
    25. """ print(root[0][2].text) """
    26. #递归遍历其下的所有子树(包括子级,子级的子级,等等)
    27. """ for neighbor in root.iter('neighbor'):
    28. print(neighbor.attrib) """
    29. print("find:===============")
    30. """ for neighbor in root.findall('neighbor'):
    31. #rank = country.find('rank').text
    32. #name = country.get('name')
    33. print(neighbor.attrib) """
    34. #print(name, rank)
    35. """ for neighbor in root.xpath('country'):
    36. print(neighbor.attrib)
    37. test = neighbor.getparent().find('rank').text
    38. print(test) """
    39. country_ref = LET.Element("neighbor")
    40. country_ref.attrib['name'] = 'china'
    41. country =root.findall('country')
    42. print(country)
    43. country[0].append(country_ref)
    44. indent(root)
    45. tree.write("d:/myself/write_arxml/country_data.xml", xml_declaration=True, encoding='utf-8')

    四、运行代码后

    五、测试用 xml文件

    1. <data>
    2. <country name="Liechtenstein">
    3. <rank>1rank>
    4. <year>2008year>
    5. <gdppc>141100gdppc>
    6. <neighbor name="Austria" direction="E"/>
    7. <neighbor name="Switzerland" direction="W"/>
    8. country>
    9. <country name="Singapore">
    10. <rank>4rank>
    11. <year>2011year>
    12. <gdppc>59900gdppc>
    13. <neighbor name="Malaysia" direction="N"/>
    14. country>
    15. <country name="Panama">
    16. <rank>68rank>
    17. <year>2011year>
    18. <gdppc>13600gdppc>
    19. <neighbor name="Costa Rica" direction="W"/>
    20. <neighbor name="Colombia" direction="E"/>
    21. country>
    22. data>

  • 相关阅读:
    【01】ES6:ECMAScript 介绍
    信号处理-卡尔曼滤波
    线上教育系统平台,企业如何才能运营呢?
    PSO、GA与simulink模型联合仿真分析(超详细算法解析)
    面试复习题--算法汇总
    Vue——状态管理库Pinia
    C++---string类的使用和模拟实现
    安装sbt利用开发工具IntelliJ IDEA编写Spark应用程序(Scala+SBT)参考林子雨教程
    API网关功能一览
    Apache Doris (四十六): Doris数据更新与删除 - 批量删除
  • 原文地址:https://blog.csdn.net/anwei20000/article/details/127935757