我无法理解如何访问 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 方法给了我元组,它看起来像我想要的唯一标识符:
[('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
关于Windows XML 输出的 Python ETREE 解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33693381/