如何使用ElementTree从xm中取出特定的xml数据

2024-05-07 00:51:14 发布

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

我得到如下的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')

Tags: clientfalsetrueattributexmlmandatoryreadonlyeid
1条回答
网友
1楼 · 发布于 2024-05-07 00:51:14

使用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)

相关问题 更多 >