Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/358.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3x:使用Python xml.etree解析具有名称空间的xml文件_Python_Python 3.x_Xml_Xml Parsing_Xml Namespaces - Fatal编程技术网

Python 3x:使用Python xml.etree解析具有名称空间的xml文件

Python 3x:使用Python xml.etree解析具有名称空间的xml文件,python,python-3.x,xml,xml-parsing,xml-namespaces,Python,Python 3.x,Xml,Xml Parsing,Xml Namespaces,我正在尝试使用xml.etree解析一个大型xml文件。它具有以下结构 我特别感兴趣的是提取具有标题的出版商的引用,如下图所示 下面是我尝试的代码示例。它不打印任何东西。感谢您的帮助 import xml.etree.ElementTree as et data = """<exist:result xmlns:exist="http://exist.sourceforge.net/NS/exist" exist:hits="

我正在尝试使用
xml.etree
解析一个大型xml文件。它具有以下结构

我特别感兴趣的是提取具有标题的出版商的引用,如下图所示

下面是我尝试的代码示例。它不打印任何东西。感谢您的帮助

import xml.etree.ElementTree as et

data = """<exist:result xmlns:exist="http://exist.sourceforge.net/NS/exist" exist:hits="1" exist:start="1" exist:count="1" exist:compilation-time="0" exist:execution-time="0">
    <events>
        <paging page="9" pageNumberOfRecords="20" totalNumberOfRecords="215"/>
        <WeatherEvent xmlns="http://hwe.niwa.co.nz/schema/2011" xmlns:gml="http://www.opengis.net/gml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://hwe.niwa.co.nz/schema/2011 ../hwe.xsd">
    <Identifier>November_2019_Timaru_Hail</Identifier>
    <Title> November 2019 Timaru Hail</Title>
    <StartDate>2019-11-20</StartDate> 
        <Abstract>A severe hailstorm over Timaru, with golf ball-sized hail stones, caused extensive damage to buildings and vehicles.</Abstract>
        <Notes/>
        <Regions>
            <Region name="Canterbury">
                <Hazards>
                    <Hazard type="Hail">
                        <Location name="Timaru">
                            <gml:Point gml:id="Timaru_1" srsName="urn:ogc:def:crs:EPSG:6.6:4326" srsDimension="2">
                                <gml:pos>-44.398445 171.255200</gml:pos>
                            </gml:Point>
                        </Location>
                        <Impacts>
                            <Impact type="InsuranceClaim" unit="$" value="130700000">Insurance claims totalled $130.7 million.</Impact>
                            
                            <Impact type="GeneralComment">Large hail stones smashed windows, pelted holes in roofs, damaged vehicles and forced the closure of businesses.</Impact>
                            <Impact type="GeneralComment">The Fire and Emergency NZ Mid-South Canterbury area commander said they had received 30 call-outs between noon and 2.40pm. Twenty one  of them were for hail or rain damage.</Impact>
                            <Impact type="GeneralComment">The South Canterbury Chamber of Commerce said there had been considerable damage and flooding with a number of businesses forced to close until their premises were secure and safe to open.  The Timaru library and the Aigantighe Art Gallery were both closed due to damage sustained.</Impact>
                            <Impact type="GeneralComment">A Timaru panel beating business estimated there were at least 10,000 vehicles in Timaru that were damaged by the hail.  Vehicles had dents, broken windscreens and broken wing mirrors.  The structural integrity of many of the damaged vehicles was found to be compromised.</Impact>
                            <Impact type="GeneralComment">An Australian-based team of hail damage repairers set up a base in Timaru to fix cars damaged in the hailstorm.  They anticipated that repairing hail-damaged cars in Timaru would take at least six months.</Impact>
                        </Impacts>
                    </Hazard>
                    <Hazard type="Hail">
                        <Location name="St Andrews">
                            <gml:Point gml:id="St_Andrews_1" srsName="urn:ogc:def:crs:EPSG:6.6:4326" srsDimension="2">
                                <gml:pos>-44.5301 171.1909</gml:pos>
                            </gml:Point>
                        </Location>
                        <Impacts>
                            <Impact type="GeneralComment">Federated Farmers reported there had been significant crop damage near St Andrews.</Impact>
                        </Impacts>
                    </Hazard>
                </Hazards>
            </Region>
        </Regions>
        <References>
            <Reference>
                <Title>Insurance Council of New Zealand (https://www.icnz.org.nz/natural-disasters/cost-of-natural-disasters/)</Title>
                <Type>Reference</Type>
            </Reference>            
            <Reference>
                <Title>Headline:  Giant hail stones hammer Timaru as storm moves up the country.</Title>
                <Type>Reference</Type>
                <Publisher>www.stuff.co.nz, 20 November 2019.  </Publisher>
            </Reference>
            <Reference>
                <Title>Headline:  Insurance companies face deluge of hail damage claims.</Title>
                <Type>Reference</Type>
                <Publisher>www.stuff.co.nz, 21 November 2019.  </Publisher>
            </Reference>
            <Reference>
                <Title>Headline:  Cars damaged in severe Timaru hailstorm failing warrents of fitness.</Title>
                <Type>Reference</Type>
                <Publisher>www.stuff.co.nz, 4 December 2019.  </Publisher>
            </Reference>
            <Reference>
                <Title>Headline:  Record insurance repairs for cars smashed by hail in Timaru.</Title>
                <Type>Reference</Type>
                <Publisher>www.stuff.co.nz, 23 December 2019.  </Publisher>
            </Reference>
            
        </References>
</WeatherEvent>
</events>
</exist:result>
"""

root = et.fromstring(data)

ns = {'exist':'http://exist.sourceforge.net/NS/exist', 'niwa':'http://hwe.niwa.co.nz/schema/2011'}


results = root.findall('exist:result', ns)
for event in results:
    weatherEvnt = event.find('niwa: events', ns)
    for WE in weatherEvnt:
        Ref = WE.find('niwa: WeatherEvent', ns)
        for x in Ref.find('niwa: References', ns):
            print(x.text)
将xml.etree.ElementTree作为et导入
data=”“”
2019年11月\u Timaru\u冰雹
2019年11月铁马鲁冰雹
2019-11-20 
蒂马鲁上空的一场严重冰雹,伴随着高尔夫球大小的冰雹,对建筑物和车辆造成了广泛的破坏。
-44.398445 171.255200
保险索赔总额为1.307亿美元。
巨大的冰雹砸碎了窗户,在屋顶上打了个洞,损坏了车辆,迫使企业关闭。
新西兰中南部坎特伯雷地区火灾和紧急情况指挥官说,从中午到下午2点40分,他们收到了30次警报,其中21次是冰雹或雨水造成的损失。
南坎特伯雷商会表示,已经发生了相当大的破坏和洪水,许多企业被迫关闭,直到其经营场所安全开放。蒂马鲁图书馆和艾甘提赫美术馆都因遭受破坏而关闭。
据Timaru的一家专门打击小组的企业估计,在Timaru至少有10000辆汽车被冰雹损坏。车辆有凹痕、挡风玻璃和翼镜破损。许多受损车辆的结构完整性被发现受到影响。
一支总部设在澳大利亚的冰雹损坏维修队在蒂马鲁建立了一个基地,以修复冰雹中受损的汽车。他们预计,在蒂马鲁修复冰雹损坏的汽车至少需要6个月的时间。
-44.5301 171.1909
联邦农场主报告说,圣安德鲁斯附近的农作物遭到严重破坏。
新西兰保险理事会(https://www.icnz.org.nz/natural-disasters/cost-of-natural-disasters/)
参考文献
标题:风暴席卷全国,巨大的冰雹冲击铁马鲁。
参考文献
www.stuff.co.nz,2019年11月20日。
标题:保险公司面临大量冰雹灾害索赔。
参考文献
www.stuff.co.nz,2019年11月21日。
标题:在严重的铁马鲁冰雹中受损的汽车健康状况不佳。
参考文献
www.stuff.co.nz,2019年12月4日。
标题:铁马鲁冰雹砸毁汽车的保险维修记录。
参考文献
www.stuff.co.nz,2019年12月23日。
"""
root=et.fromstring(数据)
ns={'exist':'http://exist.sourceforge.net/NS/exist","妮娃":"http://hwe.niwa.co.nz/schema/2011'}
results=root.findall('exist:result',ns)
对于结果中的事件:
weatherEvnt=event.find('niwa:events',ns)
对于weatherEvnt的我们:
Ref=WE.find('niwa:WeatherEvent',ns)
对于Ref.find中的x('niwa:References',ns):
打印(x.text)

问题至少包括:

  • 根目录已经存在:result,因此

    results = root.findall('exist:result', ns)
    
    返回空列表,因为
    exist:result
    没有这样的子级

  • 名称空间前缀及其本地名称后面的冒号后面不应有空格。例如,
    niwa:events
    应该是
    niwa:events

  • 没有
    niwa:References
    的文本子级

  • 不确定你的最终目标是什么但这段代码

    import xml.etree.ElementTree as et
    
    data = "" # As specified in question.
    
    root = et.fromstring(data)
    ns = {'exist':'http://exist.sourceforge.net/NS/exist',
          'niwa':'http://hwe.niwa.co.nz/schema/2011'}
    
    for ref in root.findall('.//niwa:Title', ns):
      print('Title='+ref.text)
    
    将演示如何成功选择命名空间XML中的文本,并输出:

    Title= November 2019 Timaru Hail
    Title=Insurance Council of New Zealand (https://www.icnz.org.nz/natural-disasters/cost-of-natural-disasters/)
    Title=Headline:  Giant hail stones hammer Timaru as storm moves up the country.
    Title=Headline:  Insurance companies face deluge of hail damage claims.
    Title=Headline:  Cars damaged in severe Timaru hailstorm failing warrents of fitness.
    Title=Headline:  Record insurance repairs for cars smashed by hail in Timaru.
    

    谢谢是的,这非常接近我想要的。将根据您的答案进行一些调整。