0

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

2 Answers 2

1

Use the correct XPath.

Select-Xml -XPath '//Job[@titleId and @start]' | Select -expand titleId
Sign up to request clarification or add additional context in comments.

Comments

1

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.

3 Comments

The values can vary, so I need a select rather than a where clause.
I achieved it this way, appreciate it may be long-winded but I'm not a PS expert, or developer by nature: gc "\\path\fil.xml" | Select-Xml -XPATH "//Job" | select -expandproperty node | Select titleID, start | where {$_.titleID -ne $NULL} | Select -expandproperty titleID
that's indeed a very complex solution, see my update

Your Answer

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