代码之家  ›  专栏  ›  技术社区  ›  Thomas Pichler

使用PowerShell解析XML文件

  •  0
  • Thomas Pichler  · 技术社区  · 5 年前

    我是Powershell的新手,我不想获取这个xml的所有id(xml不能更改 因为这只是我问题的一个假象)

    <?xml version="1.0" encoding="ISO-8859-1"?>
    <List>
     <Person1>
        <Id>E00023</Id>
        <empName>Aadharsh</empName> 
     </Person1>
     <Person2>
        <Id>E00042</Id>
        <empName>Raksha</empName> 
     </Person2>
    </List>
    

    通过这段代码,我只得到Person1的Id:

    $XMLfile = 'C:\test.xml'
    [XML]$empDetails = Get-Content $XMLfile
         
    foreach($module in $empDetails.List.Person1){
    Write-Host "Id :" $module.Id
    }
    

    我尝试了以下代码,但不起作用:( 问题是Person1和Person2是不同的名字。 我需要更改什么才能获得所有身份证?

    $XMLfile = 'C:\test.xml'
    [XML]$empDetails = Get-Content $XMLfile
     
    foreach($module in $empDetails.List.$module){
    Write-Host "Id :" $module.Id
    }
    
    2 回复  |  直到 5 年前
        1
  •  1
  •   RoadRunner    5 年前

    你可以迭代 XmlNode.ChildNodes :

    $XMLfile = 'C:\test.xml'
    
    [xml]$empDetails = Get-Content -Path $XMLfile
    
    foreach ($person in $empDetails.List.ChildNodes) {
        $person.Id
    }
    

    或使用 XmlNode.SelectNodes 并扩大 InnerText :

    $empDetails.List.SelectNodes("//Id").InnerText
    

    输出:

    E00023
    E00042