我很难理解如何访问powershell输出的XML格式。我用Python和etree做这个。你知道吗
XML是这些的一系列,我可以通过在根上迭代来获得:
<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>
我可以通过以下操作进入“道具”元素:
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方法为我提供了tuple,它看起来像是我要查找的唯一标识符:
[('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表达式
对你来说,这个应该管用
你可以在这里找到更多关于他们的信息:
http://www.w3schools.com/xsl/xpath_intro.asp
以及
https://docs.python.org/2/library/xml.etree.elementtree.html#xpath-support
相关问题 更多 >
编程相关推荐