Python ETREE解析windows XML输出

时间:2015-11-13 13:03:49

标签: python xml elementtree

我无法理解我应该如何访问powershell输出的XML格式。我在Python中使用etree进行此操作。

XML是这些的连续性,我可以通过itering over root来实现:

  <Obj RefId="3">
    <TNRef RefId="0" />
    <ToString>CN=Guest,CN=Users,DC=xxx,DC=xx</ToString>
    <Props>
      <S N="DistinguishedName">CN=Guest,CN=Users,DC=xxx,DC=xx</S>
      <B N="Enabled">false</B>
      <Nil N="GivenName" />
      <Obj N="MemberOf" RefId="4">
        <TNRef RefId="1" />
        <LST>
          <S>CN=Guests,CN=Builtin,DC=xxx,DC=xx</S>
        </LST>
      </Obj>
      <S N="Name">Guest</S>
      <S N="ObjectClass">user</S>
      <G N="ObjectGUID">xxxxxxx-xxxx-xxxx-xxxx-xxxxxx</G>
      <S N="SamAccountName">Guest</S>
      <Obj N="SID" RefId="5">
        <TNRef RefId="2" />
        <ToString>S-1-5-21-1111111-11111-111111111-111</ToString>
        <Props>
          <I32 N="BinaryLength">28</I32>
          <S N="AccountDomainSid">S-2-2-2-22222-222-22222</S>
          <S N="Value">S-2-2-22-2222222-222222-22222-2222</S>
        </Props>
      </Obj>
      <Nil N="Surname" />
      <Nil N="UserPrincipalName" />
    </Props>
  </Obj>

我可以通过以下方式获取“props”元素:

  tree = etree.parse(file)
  root = tree.getroot()
  props = root.find('Props')

现在让我们说我想获得“SamAccountName”,我不明白如何达到它。如果我打印元素的键,我会得到非唯一键:

['N']
['N']
['N']
['RefId', 'N']
['N']
['N']
['N']
['N']
['RefId', 'N']
['N']
['N']

items方法给了我tupple,它看起来像我之后的唯一标识符:

[('N', 'DistinguishedName')]
[('N', 'Enabled')]
[('N', 'GivenName')]
[('RefId', '4'), ('N', 'MemberOf')]
[('N', 'Name')]
[('N', 'ObjectClass')]
[('N', 'ObjectGUID')]
[('N', 'SamAccountName')]
[('RefId', '5'), ('N', 'SID')]
[('N', 'Surname')]
[('N', 'UserPrincipalName')]

我尝试了许多不同的东西:

props.find('{N}SamAccountName')
props.find('S N="SamAccountName"')

但如果一无所获。我能达到实际价值的唯一方法是:

chicken = props[7]
print(chicken.text)

我确信有更强大的方法可以解决这个问题,但我找不到正确的方法。

1 个答案:

答案 0 :(得分:1)

您需要使用XPath表达式

在你的情况下,这个应该工作

test = props.find('S/[@N="SamAccountName"]')

您可以在此处找到有关他们的更多信息:

http://www.w3schools.com/xsl/xpath_intro.asp

https://docs.python.org/2/library/xml.etree.elementtree.html#xpath-support