John Doe admin 201" /> John Doe admin 201" /> John Doe admin 201"/>

How to I get the value of the assignee tag from the following XML using Powershell

45 Views Asked by At

XML:

<?xml version="1.0" encoding="UTF-8"?>
<work-item>
    <field id="assignee">John Doe</field>
    <field id="author">admin</field>
    <field id="created">2019-06-05 10:03:38.763 -0400</field>
    <field id="description" text-type="text/plain">
.
.
.
</work-item>
$singleAssignee  = $MyXML.SelectNodes('//work-item/field[@id="assignee"]')
write ("`t" + $singleAssignee)

Output is: field

$singleAssignee  = $MyXML.SelectNodes('//work-item/field[@id="assignee"]')
write ("`t" + $singleAssignee.InnerText)

output is empty(null)

How do i get the value of the assignee id (John Doe)?

I have also tried the following, both return nothing

#$singleAssignee  = $MyXML.work-item.field.assignee
#$singleAssignee  = Select-XML -xml $MyXML -xpath "//work-item/field/@assignee"        
2

There are 2 best solutions below

2
Gordon On

@steve-gray That code is working for me, once I fix the XML. In your example the last <field> element isn't closed with a </field> tag. If that error is also in the actual XML, and you are not catching the error when you assign $MyXML, perhaps that is the actual issue? Also, you are using SelectNodes, so $singleAssignee might not be so single. This might get you a little closer.

$assignees  = $MyXML.SelectNodes('//work-item/field[@id="assignee"]')
foreach ($assignee in $assignees) {
    write ("`t$($assignee.InnerText)")
}
1
Theo On

Did you declare $MyXml as type [xml] ? If so, both $singleAssignee.InnerText or $singleAssignee.'#text' would give you the value of the field 'John Doe' :

# using the xml as here-string
[xml]$MyXml = @"
<?xml version="1.0" encoding="UTF-8"?>
<work-item>
    <field id="assignee">John Doe</field>
    <field id="author">admin</field>
    <field id="created">2019-06-05 10:03:38.763 -0400</field>
    <field id="description" text-type="text/plain"></field>
</work-item>
"@

# or if the xml is in a file, use 
# [xml]$MyXml = Get-Content -Path 'D:\test.xml' -raw # '<THE XML FILE>'

$singleAssignee  = $MyXML.SelectNodes('//work-item/field[@id="assignee"]')
$singleAssignee.'#text'