1

I am new with Powershell and I wan't to get all id's of this xml (the xml can't be changed because ist only a illustation of my problem)

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

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
}

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
}

1 Answer 1

1

You can just iterate XmlNode.ChildNodes:

$XMLfile = 'C:\test.xml'

[xml]$empDetails = Get-Content -Path $XMLfile

foreach ($person in $empDetails.List.ChildNodes) {
    $person.Id
}

Or use XmlNode.SelectNodes and expand InnerText:

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

Output:

E00023
E00042
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.