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

来源:互联网 发布:浪漫主义文学 知乎 编辑:程序博客网 时间:2024/05/15 07:34

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

import xml.etree.ElementTree as ET

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

比入往<name><name>标签中插入age子标签

1:SubElement()

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

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代表<name>的节点

a.append(node)

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

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

<?xml version='1.0' encoding='utf-8'?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">

    <application android:allowBackup="true" android:name="com.excelliance.open.LBApplication" >

        <meta-data android:name="LB_VERSION_CODE" android:value="qwer"/>
        <meta-data android:name="LEBIAN_SECID" android:value="1234"/>

    </application>

</manifest>

       

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的结构如下:
         <tag>attrib,text</tag> 每个标签末尾都有一个tail的结束符,通过判断下一个节点是子节点还是并行节点,
添加node.tail='\n\t' 或者node.tail=‘\n\t\t’就可以了。


原创粉丝点击