如何用lxml解析XML文件,获取元素属性?

2024-06-16 17:31:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一个xml描述:

    <Car xmlns="http://example.com/vocab/xml/cars#">
     <dateStarted>{{date_started|escape}}</dateStarted>
     <dateSold>{{date_sold|escape}}</dateSold>
    <name type="{{name_type}}" abbrev="{{name_abbrev}}" value="{{name_value}}" >{{name|escape}}</name>
    <brandName type="{{brand_name_type}}" abbrev="{{brand_name_abbrev}}" value="{{brand_name_value}}" >{{brand_name|escape}}</brandName>
      <maxspeed>
        <value>{{speed_value}}</value>
        <unit type="{{speed_unit_type}}" value="{{speed_unit_value}}" abbrev="{{speed_unit_abbrev}}" />
      </maxspeed>
      <route type="{{route_type}}" value="{{route_value}}" abbrev="{{route_abbrev}}">{{by_route|escape}}</route>
      <power>
        <value>{{strength_value|escape}}</value>
        <unit type="{{strength_unit_type}}" value="{{ strength_unit_value }}" abbrev="{{ strength_unit_abbrev }}" />
      </power>
      <frequency type="{{ frequency_type }}" value="{{frequency_value}}" abbrev="{{ frequency_abbrev }}">{{frequency|escape}}</frequency>  
    </Car>

我用Python编写了一个parse_car函数,要从字符串解析,请使用上述格式:

^{pr2}$

但我只得到一部分结果。在这里:它停在路线:

    <Car xmlns="http://example.com/vocab/xml/cars#">
     <dateStarted>2011-02-05</dateStarted>
     <dateStopped>2011-02-13</dateStopped>         
    <name type="http://example.com/codes/bmw#" abbrev="X6" value="BMW X6" >BMW X6</name>
    <brandName type="http://example.com/codes/bmw#" abbrev="BMW" value="BMW" >BMW</brandName>
      <maxspeed>
        <value>250</value>
        <unit type="http://example.com/codes/units#" value="miles" abbrev="mph" />
      </maxspeed>
      <route type="http://...'

下面是预期的最终结果:

    <Car xmlns="http://example.com/vocab/xml/cars#">
     <dateStarted>2011-02-05</dateStarted>
     <dateSold>2011-02-13</dateSold>
    <name type="http://example.com/codes/bmw#" abbrev="X6" value="BMW X6" >BMW X6</name>
    <brandName type="http://example.com/codes/bmw#" abbrev="BMW" value="BMW">BMW</brandName>
      <maxspeed>
        <value>250</value>
        <unit type="http://example.com/codes/units#" value="miles" abbrev="mph" />
      </maxspeed>
      <route type="http://example.com/codes/routes#" abbrev="HW" value="Highway" >Highway</route>
      <power>
        <value>{{strength_value|escape}}</value>
        <unit type="http://example.com/codes/units#" value="powerhorse" abbrev="ph" />
      </power>
      <frequency type="http://example.com/codes/frequency#" value="daily" >Daily</frequency>  
    </Car>

你能给我一些建议为什么它不起作用吗?我错过了什么吗? 非常感谢你!在


Tags: namecomhttpvalueexampletypeunitroute