Roger Clerkwell
Roger Clerkwell

Reputation: 426

How in Powershell see all XML Levels

I have a test xml and I want to get the value from this line ATTRIBUTE NAME="News- offers_OPT_EMAIL">F so I can check for the value F or T

if I do below I can get the title but how do I get the above line value.

[xml]$xml = Get-Content testFile.xml
$xml
$xml.CUSTOMERS.CUSTOMER.NAME.TITLE

sample XML code

<?xml version="1.0" encoding="UTF-8"?>
<CUSTOMERS xml:lang="en">
    <CUSTOMER CREATED_DATE="2018-01-01 05:18:53.0" GROUP_ID="" ID="95656565">
        <NAME>
            <TITLE>M</TITLE>
            <FIRST_NAME>Joe</FIRST_NAME>
            <LAST_NAME>Smith</LAST_NAME>
        </NAME>
        <GENDER/>
        <DATE_OF_BIRTH/>
        <ADDRESS>
            <ADDRESS_LINE_1>1 White House</ADDRESS_LINE_1>
            <ADDRESS_LINE_2>Old Ave</ADDRESS_LINE_2>
            <ADDRESS_LINE_3/>
            <TOWNCITY>LONDON</TOWNCITY>
            <COUNTY/>
            <POSTCODE>18659</POSTCODE>
            <COUNTRY>France</COUNTRY>
        </ADDRESS>
        <ADDRESS>
            <ADDRESS_LINE_1>175 avenue de la division Leclerc</ADDRESS_LINE_1>
            <ADDRESS_LINE_2/>
            <ADDRESS_LINE_3/>
            <TOWNCITY>Antony</TOWNCITY>
            <COUNTY/>
            <POSTCODE>92160</POSTCODE>
            <COUNTRY>France</COUNTRY>
        </ADDRESS>
        <CONTACT_DETAILS>
            <TELEPHONE MARKETING_OPT_IN="F" TYPE="MOBILE">0123456789</TELEPHONE>
            <EMAIL MARKETING_OPT_IN="F">[email protected]</EMAIL>
        </CONTACT_DETAILS>
        <ATTRIBUTE NAME="News- offers_OPT_EMAIL">F</ATTRIBUTE>
        <NOTE>NA</NOTE>
    </CUSTOMER>

Upvotes: 1

Views: 45

Answers (1)

marsze
marsze

Reputation: 17154

You could use SelectSingleNode or SelectNodes with an XPath expression. There are several options to achieve what you want, depending on your intention, but this would be one way to do it:

# finde the nodes
$nodes = $xml.SelectNodes("//*[local-name()='ATTRIBUTE'][@NAME='News- offers_OPT_EMAIL']")
# get value
$nodes.InnerText

Or if the value of the attribute doesn't matter, simply do:

$xml.customers.customer.attribute.'#text'

Upvotes: 1

Related Questions