简体   繁体   中英

Parsing xml with Powershell

I wan't to get all id's of this xml (the xml can't be changed)

<?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>

I tried following code, but I doesn't work :( The Problem is that Person1 and Person2 are differnt names. What I have to change to get all Id's?

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

With this code I get only the Id of Person1:

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

What I have to change?

First and foremost: You need to change <Person1> and <Person2> to <Person> in your XML. Don't use element names with a counter suffix, because that makes processing the XML unnecessarily hard (and because it is a completely pointless thing to do - if there are two persons described in the XML, then both of them are supposed to be <Person> ).

Doing that makes accessing the XML easy and logical:

foreach ($person in $empDetails.List.Person) {
    Write-Host "Id :" $person.Id
}

Second: You need to change the way you read XML files. Don't ever use Get-Content to read XML files. Always create an XML document object and .Load() the XML via the file path.

$empDetails = New-Object xml
$empDetails.Load('C:\test.xml')

This makes sure that the file encoding is handled correctly (ie the <?xml version="1.0" encoding="ISO-8859-1"?> ). Using Get-Content will not do that, which can lead to broken data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM