Rohit Kachroo
Rohit Kachroo

Reputation: 81

Need to edit attribute value for a node in an xml file

I am trying to edit an attribute value in a XML file with the id of the user logged in

i tried :

$user = $env:USERNAME
$xml = [xml](Get-Content "D:\Python\prm.xml")
$node = $xml.BootStrap.DataBaseAliases.LastLoginUserName
$node.SetAttribute("LastLoginUserName", "$user");

It returns an error : You cannot call a method on a null-valued expression. At D:\Python\a.ps1:5 char:1 + $node.SetAttribute("LastLoginUserName", "$user"); + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [], RuntimeException + FullyQualifiedErrorId : InvokeMethodOnNull

Also tried following:

$user = $env:USERNAME
$FileLocation = "D:\Python\prm.xml"
$File = Get-Content $FileLocation
$XML = [XML]$File
$XPpath = "/BootStrap/DataBaseAliases/LastLoginUserName"
$node = $XML.SelectNodes($XPpath)
$node | % { $_.SetAttribute("attribute-1", "$user") }
$XML.OuterXml | Out-File $FileLocation

This doesnt return any error, but xml is unchanged. XML content below:

<?xml version="1.0" encoding="utf-8"?><BootStrap MajorVersion="18" 
MinorVersion="8" PatchVersion="5" DeploymentVersion="0"><DataBaseAliases 
DefaultPMAlias="Corp_2016" LastLoginUserName="FOOUSER"><Alias>
<Name>PMDB</Name><AppType>Project Management</AppType><Connection> 
<DriverName>SQLServer</DriverName><BlobSize>-

i would like to replace FOOUSER with user currently logged in.

Upvotes: 0

Views: 142

Answers (1)

vonPryz
vonPryz

Reputation: 24071

The XPath is not pointing to proper an element, so the result is an empty set. Let's see why.

/BootStrap/DataBaseAliases/LastLoginUserName would match XML like so,

<BootStrap>
  <DatabaseAliases>
    <LastLoginUserName />
  </DatabaseAliases>
</BootStrap>

That's not what is in the sample. LastLoginUserName is an attribute of DatabaseAliases. Change the XPath to point into DataBaseAliases element and set its properties, like so:

$XPpath = "/BootStrap/DataBaseAliases"
$node = $XML.SelectNodes($XPpath)
$node | % { $_.SetAttribute("LastLoginUserName", $user) }
$XML.InnerXML

Upvotes: 1

Related Questions