pyhon模块-5

xml是实现不同语言或程序之间进行数据交换的协议,跟json差不多,但json使用起来更简单

至今很多传统公司如金融行业的很多系统的接口还主要是xml

xml是通过<>节点来区别数据结构的:

<?xml version="1.0" encoding="UTF-8" ?>
<OPTION>
    <Graphic Ver="15" ExclusiveMode="false" FullScreen="false" VSync="false" Refresh="0" TopMost="false" FixedSet="0" WindowPosX="-10" WindowPosY="2" WindowWidth="1914" WindowHeight="1006" FullScreenWidth="1920" FullScreenHeight="1080" HardwareSkinning="false">
        <Quality_User>
            <Texture Detail="2" Bias="-0.5" />
            <Water Detail="1" />
            <Effect Detail="2" />
            <Shadow ActorShadowDetail="3" SceneShadowDetail="3" />
            <Fog Detail="2" />
            <Hdr Enable="true" />
            <Glow Enable="true" />
            <DOF Enable="true" />
            <SSAO Enable="false" />
            <RimLight Enable="true" />
            <DepthFog Enable="false" />
            <Antialias Enable="true" />
            <NetworkPet Enable="true" />
            <ViewDistance Value="2" />
            <Filter MapObjectLV1="true" MapObjectVolumeFog="false" />
            <ClipDist FarPlane="156000" DecorationLOD="0.53713" Pc="6750" Pet="4050" Npc="9045" NpcSP="15000" Monster="6750" MonsterSP="15000" Boss="15000" GameObject="6750" Effect="5400" MeshEffect="4050" Decal="5400" GhostTrail="4050" DynamicLight="4050" Chain="4050" Shadow="4050" NamePlate="4050" MapObjectLV1="15000" MapObjectLV2="30000" MapObjectLV3="60000" MapObjectLV4="105000" MapObjectLV5="150000" MapObjectLV6="60000" MapObjectVolumeFog="14400" />
            <SceneTheme FogColorBlendTime="5" ShadowMoveTime="5" SkyColorBlendTime="5" SkyTextureBlendTime="5" LightPosOriMoveTime="5" SunColorBlendTime="5" />
        </Quality_User>
    </Graphic>
    <Sound Ver="2">
        <SoundMute Value="false" />
        <RepeatBGM Value="true" />
        <ExclusiveMode Value="true" />
        <VolumeBGM Volume="0.5" />
        <VolumeFX Volume="1" />
        <VolumeEnv Volume="0.7" />
        <VolumeUI Volume="0.5" />
        <VolumeVoice Volume="1" />
    </Sound>
    <UI Ver="8">
        <Battle AutoAttack="true" CounterAttack="true" SmartCasting="false" />
        <Indicate LocalPlayerName="true" PartyMemberName="true" LocalNationName="true" OtherNationName="true" MontserName="true" GuideName="true" LocalPlayerBar="true" PartyMemberBar="true" LocalNationBar="true" OtherNationBar="true" MonsterBar="true" PetName="true" NpcName="true" NpcBar="true" />
        <BattleMSG TargetDamage="true" Circumstances="true" Damage="true" DodgeOrBlock="true" HpRecovery="true" MpRecovery="true" GetExp="true" />
        <Community SlangFilter="true" NormalChatBubble="true" PartyChatBubble="true" InvitePartyRejection="false" RequestTradeRejection="false" RequestDuelRejection="false" InviteGuildRejection="false" ConnectGuideMember="true" />
        <ETC QuestTake="true" QuestComplete="true" Skill="true" Genome="true" Help="true" ShowAutoGuide="true" ShakeSensitivity="5" RotateSensitivity="1" DistStep="7" MultiThreadAnim="false" OpenEventDlg="true" OpenGuideDlg="true" />
    </UI>
</OPTION>

 xml协议在各种语言里面都是可支持的,在python中,使用下面的模块来对xml进行操作:

 

import xml.etree.ElementTree as ET

tree = ET.parse("option.xml")    #打开xml文件
root = tree.getroot()   #获取根节点
print(root.tag) #打印根节点的标签

 执行结果:

 

OPTION

 遍历整个xml:

 

for child in root:
    print(child.tag,child.attrib)   #打印孩子节点的标签和属性  

 执行结果:

 

Graphic {'WindowWidth': '1914', 'Refresh': '0', 'FullScreenHeight': '1080', 'HardwareSkinning': 'false', 'WindowHeight': '1006', 'Ver': '15', 'FixedSet': '0', 'TopMost': 'false', 'FullScreenWidth': '1920', 'WindowPosX': '-10', 'ExclusiveMode': 'false', 'WindowPosY': '2', 'VSync': 'false', 'FullScreen': 'false'}
Sound {'Ver': '2'}
UI {'Ver': '8'}

 遍历指定属性:

 

for child in root:
    for i in child.iter('Quality_User'):    #指定遍历Quality_User
        for x in i:
            print(x.tag,x.text,x.attrib)    #text是值

 执行结果:

 

Texture None {'Detail': '2', 'Bias': '-0.5'}
Water None {'Detail': '1'}
Effect None {'Detail': '2'}
Shadow None {'SceneShadowDetail': '3', 'ActorShadowDetail': '3'}
Fog None {'Detail': '2'}
Hdr None {'Enable': 'true'}
Glow None {'Enable': 'true'}
DOF None {'Enable': 'true'}
SSAO None {'Enable': 'false'}
RimLight None {'Enable': 'true'}
DepthFog None {'Enable': 'false'}
Antialias None {'Enable': 'true'}
NetworkPet None {'Enable': 'true'}
ViewDistance None {'Value': '2'}
Filter None {'MapObjectLV1': 'true', 'MapObjectVolumeFog': 'false'}
ClipDist None {'Boss': '15000', 'Monster': '6750', 'Pc': '6750', 'MapObjectVolumeFog': '14400', 'Chain': '4050', 'Pet': '4050', 'MapObjectLV4': '105000', 'MapObjectLV2': '30000', 'FarPlane': '156000', 'NamePlate': '4050', 'Effect': '5400', 'DynamicLight': '4050', 'MonsterSP': '15000', 'MapObjectLV6': '60000', 'MeshEffect': '4050', 'DecorationLOD': '0.53713', 'MapObjectLV5': '150000', 'GameObject': '6750', 'Decal': '5400', 'Npc': '9045', 'NpcSP': '15000', 'Shadow': '4050', 'MapObjectLV3': '60000', 'GhostTrail': '4050', 'MapObjectLV1': '15000'}
SceneTheme None {'SunColorBlendTime': '5', 'ShadowMoveTime': '5', 'FogColorBlendTime': '5', 'SkyTextureBlendTime': '5', 'SkyColorBlendTime': '5', 'LightPosOriMoveTime': '5'}

 修改:

 

for child in root:
    for i in child.iter('Quality_User'):
        for x in i.iter('Water'):
            print(x.tag, x.text, x.attrib)  # text是值
            new_detail = '2'
            x.text = str(new_detail)    #新增值为2
            x.set("changed",'yes')      #set,增加标签属性“changed”,值为“yes”

tree.write('option.xml')

 执行完成后,文件更新为

            <Texture Bias="-0.5" Detail="2" />
            <Water Detail="1" changed="yes">2</Water>
            <Effect Detail="2" />
            <Shadow ActorShadowDetail="3" SceneShadowDetail="3" />

 删除:

 将刚刚修改的‘Water’节点信息删除掉:

for child in root:
    for node in child.iter('Quality_User'):
        for key in node.findall('Water'):
            print(key.tag,key.text,key.attrib)
            if key.tag == 'Water':
                node.remove(key)

tree.write('option2.xml')

 为了区分,我们将信息保存在option2.xml中

 执行完成后,option2.xml中,已经没有了刚刚的‘Water’节点: 

            <Texture Bias="-0.5" Detail="2" />
            <Effect Detail="2" />
            <Shadow ActorShadowDetail="3" SceneShadowDetail="3" />

 创建xml文档:

 

xml2 = ET.Element("Member")
name = ET.SubElement(xml2,'person1',attrib={'name':'s1','enroll':'yes'})    #创建根节点person1,属性有name,enroall
age = ET.SubElement(name,'age',attrib={'checked':'no'}) #创建孩子节点age,属性有checked
age.text = '24' #age的内容为24
sex = ET.SubElement(name,'sex') #创建孩子节点sex
sex.text = 'Female' #sex的内容为Female
name2 = ET.SubElement(xml2,'person2',attrib={'name':'s2','enroll':'no'})
age2 = ET.SubElement(name2,'age',attrib={'checked':'yes'})
age2.text = '32'
sex2 = ET.SubElement(name2,'sex')
sex2.text = 'Male'


et = ET.ElementTree(xml2)
et.write('test4.xml',encoding='utf-8',xml_declaration=True)

 注意,xml_declaration = True,是指在xml中生成申明:

<?xml version='1.0' encoding='utf-8'?>

 执行完成后,会生成test4.xml文件:

<?xml version='1.0' encoding='utf-8'?>
<Member>
    <person1 enroll="yes" name="s1">
        <age checked="no">24</age>
        <sex>Female</sex>
    </person1>
    <person2 enroll="no" name="s2">
        <age checked="yes">32</age>
        <sex>Male</sex>
    </person2>
</Member>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值