0

I have the following XML file. In this I want to filter all the city names that have employees with age 23.

Kindly help me with a PowerShell script.

I am expecting the answer "Chennai, Banglore".

<?xml version="1.0" ?>
    <customers>
<city name="Chennai">
    <Name>Anand</Name>
    <Id>123</Id>
    <Age>23</Age>
</city>
<city name="Banglore">
    <Name>Arun</Name>
    <Id>321</Id>
    <Age>23</Age>
</city>
<city name="Mumbai">
    <Name>Ashok</Name>
    <Id>1</Id>
    <Age>22</Age>
</city>

I have the following code to get the list of city names,

[xml]$test = Get-Content D:\test.xml
$names = $test.SelectNodes("/customers/city")
$sno = 0
foreach($node in $names)
{
    $sno++
    $id = $node.getAttribute("name")
    Write-Host $sno $id
}

But how do I to filter the data?

2
  • 3
    1) Your XML is malformed, as customers element is not closed. 2) Show some effort in trying to solve the problem and ask for help for specific problem. Commented Apr 3, 2013 at 6:42
  • Chennai and Banglore are in two different city-nodes. You won't recieve Chenai, Banglore as one value without unless you combine the two values yourself. Commented Apr 3, 2013 at 7:21

1 Answer 1

4

Learn about XPath and how to query XML documents. The key is to use a predicate to filter the data: /customers/city[Age=23]. Like so,

$names = $test.SelectNodes("/customers/city[Age=23]")
$sno = 0
foreach($node in $names) {
    $sno++
    $id = $node.getAttribute("name")
    Write-Host $sno $id
}

Output:

1 Chennai
2 Banglore
Sign up to request clarification or add additional context in comments.

1 Comment

Note that XPath expressions are case-sensitive. Also, you can directly select the city names without the additional getAttribute(): //city[Age=23]/@name.

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.