0
点赞
收藏
分享

微信扫一扫

阅读开源python脚本工具学习笔记2,之解析xml

_阿瑶 2022-04-26 阅读 47
python

这个开源脚本解析xml 使用 xml.etree.ElementTree工具

下面的理解全部参照
python 官方文档

注意使用xml 需要注意

原文:
Warning The xml.etree.ElementTree module is not secure against maliciously constructed data. If you need to parse untrusted or unauthenticated data see XML vulnerabilities.

xml.etree.ElementTree 不是安全的解析工具,对于不信任的或者为认证过的 xml 文件,最好不要使用。

Parsing XML

country_data.xml 文件

<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank>1</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Singapore">
        <rank>4</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
    <country name="Panama">
        <rank>68</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/>
    </country>
</data>

首先获取根节点,并打印出来根节点名称。

import xml.etree.ElementTree as ET


class study:
    def __init__(self,xml):
        self.xml = xml
    
    def getroot(self):
        tree = ET.parse(self.xml)
        self.root = tree.getroot()
        print("root.tag=",self.root.tag)

if __name__ == "__main__":
    s = study("country_data.xml")
    s.getroot()

结果:

root.tag= data
举报

相关推荐

0 条评论