python 解析xml,并修改,插入标签。以及出现ns0的问题,和缩进问题。

您所在的位置:网站首页 分析如何在python中解析和修改xml python 解析xml,并修改,插入标签。以及出现ns0的问题,和缩进问题。

python 解析xml,并修改,插入标签。以及出现ns0的问题,和缩进问题。

2023-06-20 01:25| 来源: 网络整理| 查看: 265

本文章采用xml.etree.ElementTree 库进行解析XML,和insert

import xml.etree.ElementTree as ET

目前了解的往xml插入node的三种方法:

比入往标签中插入age子标签

1:SubElement()

node=ET.SubElement(a."age")    //a代表的节点

node.set("andriod:name",key)

node.set("andriod:value",lb_version)        

2:采用Element() 和append()的方法:

node=ET.Element("age")

 

node.set("andriod:name",key)

 

node.set("andriod:value",lb_version) //a代表的节点

 

a.append(node)

3:采用Element() 和insert()的方法:

insert方法可以对标签进行精确的插入,具体还没有试过,那下面就来看项目中出现的问题,和解决办法,以下是要进行插入后的xml

 

 

   

                     

       

def add_andriod_node(self,filepath,key,value):

 

        ET.register_namespace('android','http://schemas.android.com/apk/res/android')         tree=ET.parse(filepath)         root=tree.getroot()         node=ET.Element("meta-data")         node.set("andriod:name",key)

 

        node.set("andriod:value",value)

        node.tail="\n\t"

        for i in root.iter("application"):             for child in i:                 pass         child.tail='\n\t\t'

 

        for a in root.iter("application"):

 

            a.append(node)

            break

        tree.write(filepath,encoding="utf-8",xml_declaration=True)

if __name__=='__nain__':

     add("文件名","LEBIAN_SECID","1234")

     add("文件名","LB_VERSION_CODE","qwer")

 

 

1>首先来接解决,用xml.etree.ElementTree来处理xml出现ns0的问题。

 

xml.etree.ElementTree.register_namespace(prefix,uri)

Registers a namespace prefix. The registry is global, and any existing mapping for either the given prefix or the namespace URI will be removed.prefix is a namespace prefix. uri is a namespace uri. Tags and attributes in this namespace will be serialized with the given prefix, if at all possible

         这句话的意思就是说xml文件里面的命名空间会被移除掉,为了防止这种情况发生,就要调用该方法重新对前缀和命名空间进行序列化

ET.register_namespace('android','http://schemas.android.com/apk/res/android')

2>下来就是缩进的问题:

xml的结构如下:

         attrib,text 每个标签末尾都有一个tail的结束符,通过判断下一个节点是子节点还是并行节点,

添加node.tail='\n\t' 或者node.tail=‘\n\t\t’就可以了。

 

 



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3