SelectSingleNode() results in null value

I readily admit that I don't understand XML but I'm trying to learn. That said, I've hit a dead end with my learning on this one particular problem.

First, I've seen the thread at this link, but its solution wasn't helpful: XML Document SelectSingleNode returns null You can see I've added some of the suggested code below and it has resulted in the same behavior.

I'm trying to append a list of printers to an XML document that looks pretty much like this:

<?xml version="1.0" encoding="UTF-8"?>
<REMOTE_PRINTING_NODE>
  <PRINTING_PARAMETERS_FILE>
  </PRINTING_PARAMETERS_FILE>
  <PRINTER_MAPPINGS>
    <PRINTER_MAPPING>
      <PHYSICAL>\\Server\Printer_1</PHYSICAL>
      <LOGICAL>Printer_1</LOGICAL>
    </PRINTER_MAPPING>
    <PRINTER_MAPPING>
      <PHYSICAL>\\Server\Printer_2</PHYSICAL>
      <LOGICAL>Printer_2</LOGICAL>
    </PRINTER_MAPPING>
  </PRINTER_MAPPINGS>
</REMOTE_PRINTING_NODE>

And here is the code to import, append and save the XML data:

Install-Module PSExcel

$xml = [xml](Get-Content "C:\printer.xml")
$printerList = (Import-XLSX "C:\Printers.xlsx")

$ns = New-Object xml.xmlnamespacemanager($xml.NameTable)
$ns.AddNameSpace("x", "http://microsoft.com/GroupPolicy/GPOOperations/MigrationTable")

forEach ($printer in $printerList) {

    $mapEl = $xml.CreateElement("PRINTER_MAPPING")
    $LogEl = $xml.CreateElement("LOGICAL")
    $PhyEl = $xml.CreateElement("PHYSICAL")

    $PhyEl.AppendChild($xml.CreateTextNode("$($printer.Physical)"))
    $LogEl.appendChild($xml.CreateTextNode("$($printer.logical)"))

    $mapEl.AppendChild($PhyEl)
    $mapEl.AppendChild($LogEl)

    $mappings = $xml.SelectSingleNode("/x:REMOTE_PRINTING_NODE/x:PRINTER_MAPPINGS", $ns)
    $mappings.AppendChild($mapEl)

}
    
$xml.save("C:\printer.xml")

The problem I run into is with this line:

$mappings.AppendChild($mapEl)

Each iteration through the foreach loop fails to append the built XML data to the document because $mappings is null. I'm not sure where to go from here. Thanks.



Read more here: https://stackoverflow.com/questions/66992279/selectsinglenode-results-in-null-value

Content Attribution

This content was originally published by triborro at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: