Search code examples
xmlwindowspowershellcdata

How to access XML data inside CDATA with Powershell


I'm pretty new to Powershell so bear with me if this seems like a simple question. I'm trying to access info inside a CDATA tag, however I can't seem to do it. This is the xml file:

example.xml

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<fooMaster>
    <fooFirst>Hello there</fooFirst>
    <fooCDATA>
        <![CDATA[<?xml version="1.0" encoding="UTF-8"?>
        <fooChild>
            <data>
                Hello everyone
            </data>
        </fooChild>]]>
    </fooCDATA>
</fooMaster>

And this one is my ps1 file:

script.ps1

$XMLfile = 'example.xml'
[XML]$file = Get-Content $XMLfile

write-Host "fooFirst contains: " $file.fooMaster.fooFirst
write-Host "data contains: " $file.fooMaster.fooCDATA."#cdata-section".fooChild.data

Read-Host -Prompt "Press Enter to exit"

$file.fooMaster.fooFirst works perfectly and displays Hello there, however the line below that one doesn't work. I read somewhere that adding .#cdata-section would display information inside CDATA tags, and it does! but it displays everything as if it was plain text, is there a way to not only access the information inside the CDATA but also use it like a regular xml.


Solution

  • To access the elements inside CDATA get into another variable:

    [xml]$cdata = $file.fooMaster.fooCDATA."#cdata-section"
    write-Host "data contains: $($cdata.fooChild.data.tostring().trim())