[英]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 我正在尝试使用登录用户的ID编辑XML文件中的属性值
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"); 在D:\\ Python \\ a.ps1:5 char:1 + $ node.SetAttribute(“ LastLoginUserName”,“ $ user”); + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [], RuntimeException + FullyQualifiedErrorId : InvokeMethodOnNull + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + 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不变。 XML content below: XML内容如下:
<?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. 我想用当前登录的用户替换FOOUSER。
The XPath is not pointing to proper an element, so the result is an empty set. XPath没有指向适当的元素,因此结果是一个空集。 Let's see why. 让我们看看为什么。
/BootStrap/DataBaseAliases/LastLoginUserName
would match XML like so, /BootStrap/DataBaseAliases/LastLoginUserName
会像这样匹配XML,
<BootStrap>
<DatabaseAliases>
<LastLoginUserName />
</DatabaseAliases>
</BootStrap>
That's not what is in the sample. 那不是样本中的内容。 LastLoginUserName
is an attribute of DatabaseAliases
. LastLoginUserName
是DatabaseAliases
的属性 。 Change the XPath to point into DataBaseAliases element and set its properties, like so: 更改XPath使其指向DataBaseAliases元素并设置其属性,如下所示:
$XPpath = "/BootStrap/DataBaseAliases"
$node = $XML.SelectNodes($XPpath)
$node | % { $_.SetAttribute("LastLoginUserName", $user) }
$XML.InnerXML
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.