Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Powershell,遍历XML。获取父节点属性,在子节点属性上搜索_Xml_Powershell_Tree Traversal - Fatal编程技术网

Powershell,遍历XML。获取父节点属性,在子节点属性上搜索

Powershell,遍历XML。获取父节点属性,在子节点属性上搜索,xml,powershell,tree-traversal,Xml,Powershell,Tree Traversal,我有这种用户/角色的XML模式 <Department/> <JobTitle/> <Language/> <Roles> <UserRole public-id="pc:2001"> <Role public-id="superuser"/> <User public-id="system:44"/> </UserRol

我有这种用户/角色的XML模式

<Department/>
<JobTitle/>
<Language/>

<Roles>
  <UserRole public-id="pc:2001">
    <Role public-id="superuser"/>
    <User public-id="system:44"/>
  </UserRole>
  <UserRole public-id="usrrol:48">
    <Role public-id="underwriter_supervisor"/>
    <User public-id="system:44"/>
  </UserRole>
  <UserRole public-id="usrrol:49">
    <Role public-id="user_admin"/>
    <User public-id="system:44"/>
  </UserRole>
</Roles>

您需要引用属性,因为它有一个破折号。另外,我没有看到
GetParent()
方法,但是
get\u ParentNode()
有效

foreach ($user in $xml.import.User.Roles.UserRole.User) {
    if ($user.'public-id' -eq 'system:44') {
    $userRole = $user.Get_ParentNode()
    write-host "Role -" $userRole.Role.'public-id'
    }
}
另外,在写主机(publid id)的行中有一个输入错误

输出

Role - superuser
Role - underwriter_supervisor
Role - user_admin

您可能可以使用Select Xml和xpath对其进行简化(这假设您上面的Xml是封装在属性中的,并且是打开和关闭标记:

foreach ($user in $xml | Select-Xml ".//UserRole[./User[@public-id='system:44']]//Role/@public-id") {    
    write-host "Role - " $user
    }
foreach ($user in $xml | Select-Xml ".//UserRole[./User[@public-id='system:44']]//Role/@public-id") {    
    write-host "Role - " $user
    }