user310291
user310291

Reputation: 38228

Why does SelectSingleNode return null object?

I have $metas which is null so that AppendChild failed. Why does SelectSingleNode returns a null object in my code :

$xml=[xml]@'
<?xml version="1.0" encoding="iso-8859-1"?>
<catalogue>
  <products>
    <product id="pdt1">
      <metas>
      </metas>
    </product>
    <product id="pdt2">
      <metas>
      </metas>
    </product>    
  </products>
</catalogue>
'@

$product_code = "pdt2"

$metas = $xml.SelectSingleNode("//catalogue/products/product[@code='$product_code']/metas")


$attr=$xml.CreateAttribute("date");                            
$attr.Value = "2015.07.24"
$metas.Attributes.Append($attr) 

$newmeta1 = $xml.CreateElement('meta')
$attr1=$xml.CreateAttribute("code");  
$attr1.Value = "123456"
$newmeta1.Attributes.Append($attr1) 

$metas.AppendChild($newmeta1) 

Upvotes: 2

Views: 351

Answers (1)

djs
djs

Reputation: 1700

Your product XML node doesn't have a code attribute. Rather, it has an id attribute. Therefore, you should use [@id=...] instead of [@code=...].

Try this:

$metas = $xml.SelectSingleNode("//catalogue/products/product[@id='$product_code']/metas")

Upvotes: 2

Related Questions