kamokoba
kamokoba

Reputation: 597

PowerShell & XML: cannot extract InnerText value if text is preceded by a dot

Sample XML file:

<input>
    <filePattern>
        <midfix>.bof-fix</midfix>
        <format>raw</format>
    </filePattern>
</input>

If I try to extract the text from "format" element, the following script works OK:

Get-ChildItem -Path "C:\ps_scripts\configs\*" -Recurse |
ForEach-Object {
    $xml_file = $_
    $curr_dir = $xml_file
    $content = [xml](Get-Content $curr_dir)
    $nodes = $content.SelectNodes("//input")
    
    foreach ($node in $nodes) {
        $format = $node.SelectNodes('filePattern/format').InnerText
        $format
        
    }        
}

The output is:

raw

But if I modify the above script by replacing the 2 lines in foreach loop with this:

$midfix = $content.SelectNodes('filePattern/midfix').InnerText 
$midfix

then there is no output at all. Expected output:

.bof-fix

Apparently this is because of the leading dot (.) in the text?

Upvotes: 1

Views: 328

Answers (1)

Jack Fleeting
Jack Fleeting

Reputation: 24940

I don't know if it's going to work with PS 5.0, but try it this way and see if it works:

$nodes = $xml.SelectSingleNode("//midfix")
foreach ($node in $nodes) {
        $format = $node.InnerText
         $format        
    } 

Edit: To refelct comment below: change

$nodes = $xml.SelectSingleNode("//midfix")

to

$nodes = $xml.SelectSingleNode("//input//midfix")

Upvotes: 1

Related Questions