xml拾遗

解析xml

from xml.etree import ElementTree as ET
#打开读取xml内容
str_xml = open("文件名.xml","r").read()
#将字符串解析成xml一个特殊对象,root代指xml文件的根节点
root = ET.XML(str_xml)
from xml.etree import ElemenetTree as ET
tree = ET.parse("文件名.xml")   #解析xml文件
root = tree.getroot()             #解析成特殊的对象,特殊的对象我们称之为根节点

 

from xml.etree import ElementTree as ET

tree = ET.parse("文件名".xml)
root = tree.getroot()
print(root.tag)        #tag:获取属性         
print(root.attrib)    #默认是一个空的字典,可以自定义写入

#attrib:获取标签

#parse:解析
#getroot:根节点
#创建节点    ##Element类型
from xml.etree import ElementTree as ET
tree = ET.parse("first.xml")
root = tree.getroot()
son = root.makeelement("tt",{"wyc":"123"})
s = son.makeelement("tt",{"ryf":"456})
son.append(s)         #在son子节点底下追加s孙节点
root.append(son)  #在根节点下边追加son子节点
tree.write("qq.xml")    

#parse:获取属性
#getpass:根节点
#makeelement:创建节点
#append:追加
#write:写

 

from xml.etree import ElementTree as ET
tree = ET.parse("first.xml")
root = tree.getroot()
son = root.makeelement("tt",{"wyc":"123"})
root.append(son)
tree.write("hh.xml")


#makeelement:创建节点
#parse:解析
#getroot:根节点
#append:追加
#write:写
#第二种创建节点方式,直接用类创建
from xml.etree import ElementTree as ET
tree = ET.parse("first.xml")
root = tree.getroot()
son = ET.Element("tt",{"wyc":""123})
s = ET.Element("tt",{"ryf":"456"})
root.append(son)
son.append(s)

tree.write("qq.xml")
#第三种创建方式SubElement
from xml.etree import ElementTree as ET
root = ET.Element("nihao",{"hh":"123"})
ET.SubElement(root,"nihao",{"age":"18"})
tree = EL.Element(root)
tree.write("qq.xml")
###加汉字必须得加encoding = "utf-8"
from xml.etree import ElementTree as ET
root = ET.Element("nihao",{"hh":"123"})
ET.SubElement(root,"nihao",{"age":"贰拾"})
tree = ET.Element(root)
tree.write("qq.xml",encoding = "utf-8")



#result

<nihao hh="123">
    <nihao agr="贰拾" />
</nihao>
#顶端加注释
from xml.ertee import ElementTree as ET
root = ET.Elemen("nihao",{"hh":"123"})
ET.SubElement(root,"nihao",{"age":"贰拾"})
tree = ET.Element(root)
tree.write("qq.xml",encoding = "utf-8",xml_declaration=True)


#result
<?xml version='1.0' encoding='utf-8'?>       #解释目前用的是1.0的版本
<nihao hh="123">
    <nihao agr="贰拾" />
</nihao>

 

 

posted @ 2016-05-26 16:49  WrYcF  阅读(91)  评论(0编辑  收藏  举报
Live2D