【问题标题】:how to use ElementTree to take out particular xml data from xml如何使用 ElementTree 从 xml 中取出特定的 xml 数据
【发布时间】:2016-05-06 09:31:58
【问题描述】:

我收到如下的 xml 响应

<entitlement>
  <externalId></externalId>
  <entitlementAsWhole>false</entitlementAsWhole>
  <eId>1c7fd51c-8f12-46e8-a4b7-f1f9c614df82</eId>
 <entitlementType>PARENT</entitlementType>
 <linkedEntId/>
   <product>
    <productIdentifier>
      <prdExternalId></prdExternalId>
      <productId>7</productId>
      <productNameVersion>
        <productName>test2_porduct</productName>
        <productVersion>1.0.0</productVersion>
      </productNameVersion>
    </productIdentifier>
    <feature>
      <featureIdentifier>
        <ftrExternalId></ftrExternalId>
        <featureId>7</featureId>
        <featureIdentity>null</featureIdentity>
        <ftrNameVersion>
          <featureName>test2_feature</featureName>
          <featureVersion>1.0.0</featureVersion>
        </ftrNameVersion>
      </featureIdentifier>
      <activationAttributes>
    <attributeGroup groupName="LOCKING">
      <attribute>
        <attributeName>CLIENT_1_CRITERIA</attributeName>
        <attributeValue>4</attributeValue>
        <readOnly>true</readOnly>
        <mandatory>false</mandatory>
      </attribute>
      <attribute>
        <attributeName>CLIENT_1_INFO</attributeName>
        <attributeValue></attributeValue>
        <readOnly>false</readOnly>
        <mandatory>true</mandatory>
      </attribute>
    </attributeGroup>
  </activationAttributes>
  <entitlementItemAttributes/>
</Item>
 </productKey>
 <entitlementAttributes/>
</entitlement>

我想从上面的 xml 中获取只有激活属性的 xml,如下所示:-

<activationAttributes>
    <attributeGroup groupName="LOCKING">
      <attribute>
        <attributeName>CLIENT_1_CRITERIA</attributeName>
        <attributeValue>4</attributeValue>
        <readOnly>true</readOnly>
        <mandatory>false</mandatory>
      </attribute>
      <attribute>
        <attributeName>CLIENT_1_INFO</attributeName>
        <attributeValue></attributeValue>
        <readOnly>false</readOnly>
        <mandatory>true</mandatory>
      </attribute>
    </attributeGroup>
  </activationAttributes>

我该怎么做我尝试如下 resp.txt 包含原始 xml 然而它没有帮助

activation_attribute = et.fromstring(resp.text).findall('activationAttributes')

【问题讨论】:

    标签: python python-2.7 elementtree celementtree


    【解决方案1】:

    使用find() 只获取一个元素,然后使用tostring() 获取所选元素的原始XML 表示:

    from xml.etree import cElementTree as et
    
    .....
    
    root = et.fromstring(resp.text)
    activation_attribute = root.find('.//activationAttributes')
    print et.tostring(activation_attribute)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-01
      • 2015-08-27
      • 1970-01-01
      • 2013-02-04
      • 2017-07-19
      • 1970-01-01
      • 2020-10-22
      相关资源
      最近更新 更多