Python windows XML 输出的 ETREE 解析

Python ETREE parsing of a windows XML output

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

XML 是这些的连续体,我可以通过遍历 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)

我确定有更可靠的方法可以做到这一点,但我找不到正确的方法。

您需要使用 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