狂自私

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

python解析xml

主要是查询标签:

复制代码
import xml.dom.minidom

s='''xml字符串'''

'''
这里做一些解释:
<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <soapenv:Body>  #这种形式的,前面的soapenv表示命名空间url(namespaceURI),需要使用getElementsByTagNameNS来查找,若要使用getElementsByTagName()查找,就必须带上完整的namespaceURI:tagname(此处就是soapenv:Body)
        <ns1:vRBTOneKeyPress soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:ns1="http://impl.crbt.cmcc.com">
            <event href="#id0"/>
        </ns1:vRBTOneKeyPress>
        <multiRef id="id0" soapenc:root="0" soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xsi:type="ns2:VRBTOneKeyPressEvt" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:ns2="http://schemas.crbt.cmcc.com">
            <DID xsi:type="xsd:string">xxxxxxxxxx</DID>
            <DIDPwd xsi:type="xsd:string">xxxxxxxxxx</DIDPwd>
            <SEQ xsi:type="xsd:string">xxxxxxxxxx</SEQ>
            <calledNumber xsi:type="xsd:string">xxxxxxxxxx</calledNumber>
            <callingNumber xsi:type="xsd:string">xxxxxxxxxx</callingNumber>
            <key xsi:type="xsd:string">xxxxxxxxxx</key>
            <timeStamp xsi:type="xsd:string">xxxxxxxxxx</timeStamp>    #这种前面不带namespaceURI的,就可以直接使用getElementsByTagName()查找
            <toneID xsi:type="xsd:string">xxxxxxxxxx</toneID>
            <playScene xsi:type="xsd:string">xxxxxxxxxx</playScene>
            <pressType xsi:type="xsd:string">xxxxxxxxxx</pressType>
            <callID xsi:type="xsd:string">xxxxxxxxxx</callID>
        </multiRef>
    </soapenv:Body>
</soapenv:Envelope>
'''


DOMTree = xml.dom.minidom.parseString(s)
collection = DOMTree.documentElement        #文档
namespaceUrl = collection.namespaceURI        #命名空间
body = collection.getElementsByTagName('timeStamp')    #查询该标签,返回的是一个列表
print(body[0].firstChild.data)        #获取标签的内容,按照示例文本,这里输出为xxxxxxxxxx
复制代码

 

posted on   狂自私  阅读(73)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示