Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to read only first leaf of xml attribute

I have Powershell code like this:

$Xml = @"
<?xml version="1.0" encoding="utf-8"?>
<DisplayDefinitionTable>
    <columns>
        <column_entry order_num="0" relation_to_base="Item.current_name">current_name</column_entry>
    </columns>
    <rows>
        <row>
            <object_tag tag="91859" uid="TdjJhBMdpQNFhC"/>
            <object_tag tag="86504" uid="TtvJBp53pQNFhC"/>
            <row_element column="0" component_tag="91859" property_name="current_name">EAUX</row_element>
        </row>
        <row>
            <object_tag tag="92069" uid="DCuJhBMdpQNFhC"/>
            <object_tag tag="86504" uid="TtvJBp53pQNFhC"/>
            <row_element column="0" component_tag="92069" property_name="current_name">VISS</row_element>
        </row>
    </rows>
</DisplayDefinitionTable>

"@

Select-Xml -Content $Xml -XPath "//object_tag" | foreach {$_.node.uid}

And results:

Select-Xml -Content $Xml -XPath "//object_tag" | foreach {$_.node.uid}


TdjJhBMdpQNFhC
TtvJBp53pQNFhC
DCuJhBMdpQNFhC
TtvJBp53pQNFhC

PS C:\Windows\system32> 

The main goal is to take only first uid value of every leaf in the file so proper answer should looks like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

TdjJhBMdpQNFhC
DCuJhBMdpQNFhC


PS C:\Windows\system32> 

How to do this??
Thanks

>Solution :

Try specifying your command as:

Select-Xml -Content $Xml -XPath "//object_tag[1]" | foreach {$_.node.uid}

Note, the addition of the [1] to the XPath to specifically pull just the first instance.

Or you also could have your command like the below to save piping to the foreach:

(Select-Xml -Content $Xml -XPath "//object_tag[1]").node.uid

Both variations above give you the results you’re looking for.

Also, this great cheat sheet on XPath has some further information on indexing, etc…

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading