Reputation: 741
Below is an extract of an xml file
<JobList>
<Job id="Hotel" start="2016-10-06" />
<Job id="Cleaning" start="2016-10-06" />
<Job id="Floor" start="2016-10-06" />
<Job id="Training" start="2016-10-06" />
<Job id="Meeting" start="2016-10-06" />
<Job id="CI" start="2016-10-06" />
<Job titleId="Kitchen Associate" id="Kitchen" start="2016-10-06" rank="18">
In need to return the "titleId" and "start" from the last line.
If I write the following code I can get the titleId, "Kitchen Associate" no problems.
gc "\\path\fil.xml" | Select-Xml -XPATH "//Job/@start" | select * -expandproperty node | Select titleID
But I can't seem to return the RELATED start date as it will return back all seven of the start dates from the JobList. Is there a way of limiting the results such that it only takes it from where titleID also exists?
Thanks
Upvotes: 0
Views: 41
Reputation: 13483
The problem with your code is that the approach you took is oriented towards getting attributes from different nodes, when you should get the correct node and then select its attribute. You can achieve it with XPath as well:
(gc "e:\1.txt" -Raw | Select-Xml -XPATH "//Job[@titleId]/@start").Node
but here's a more Powershell way of doing this:
$xml = [xml] (gc e:\1.txt -Raw)
$node = $xml.JobList.Job | Where-Object { $_.titleId -ne $null }
$node.start
You first select the correct node based on the titleId
attribute and then you have access to all of its attributes.
Keep in mind that there's a chance that there will be more than 1 or no nodes at all that have the required titleId
, so you need to check that $node
is not null and how many nodes are there.
Upvotes: 1
Reputation: 73506
Use the correct XPath.
Select-Xml -XPath '//Job[@titleId and @start]' | Select -expand titleId
Upvotes: 1