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)
a.append(node)
3:采用Element() 和insert()的方法:
insert方法可以对标签进行精确的插入,具体还没有试过,
那下面就来看项目中出现的问题,和解决办法,以下是要进行插入后的xml
<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'
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’就可以了。
- python 解析xml,并修改,插入标签。以及出现ns0的问题,和缩进问题。
- python的缩进问题!
- DOM解析XML的缩进问题(JAVA)
- SAX解析xml出现的问题
- Python 缩进问题
- python中的缩进问题
- Python缩进问题
- python中的缩进问题
- Python语言代码缩进的问题
- python:在for遍历list时使用remove出现的问题以及解析
- XML中配置dubbo相关标签不能解析的问题
- UE和SI的代码缩进问题
- Python解析xml文件遇到的编码解析的问题
- python基础教程之缩进问题
- KXML2解析xml出现的问题及解决办法
- ava7 解析xml文件出现莫名其妙的有关问题
- [Python]计算闰年时候出现的and和or优先级的问题以及短路逻辑
- python 导入MySQLdb模块 出现的问题 并测试
- C语言经典项目之二——扫雷
- 1自己常用Linux常用命令
- S5PV210的启动过程详解(一)
- 【洛谷2982】[Usaco2010 Feb]慢下来Slowdown(dfs序+线段树)
- [BZOJ3669][NOI2014]魔法森林(LCT)
- python 解析xml,并修改,插入标签。以及出现ns0的问题,和缩进问题。
- 在Dialog布局中添加ListView
- jquery 获取textarea文本值详解
- [BZOJ4475][JSOI2015]子集选取(DP+结论)
- 1自己常用windows命令
- SLAM方法汇总
- java 行为模式 状态模式
- SpringBoot入门-3(返回json数据)
- [BZOJ1026][SCOI2009]windy数(数位DP)