使用powershell向xml添加一个新元素
本文关键字:一个 新元素 元素 powershell xml 添加 使用 | 更新日期: 2023-09-27 18:15:21
我有一个如下所示的XML文件
<xml xmlns="http://schemas.microsoft.com/wix/2006/wi">
<Product>
<Feature Id="f1" Absent="qqq" Title="test" Level="1">
<ComponentGroupRef Id="ComponentGroupRef1" />
<ComponentGroupRef Id="ComponentGroupRef2" />
<ComponentGroupRef Id="ComponentGroupRef3" />
<ComponentGroupRef Id="ComponentGroupRef4" />
<ComponentGroupRef Id="WindowsFolder1" />
<ComponentGroupRef Id="ComponentGroupRef5" />
<ComponentGroupRef Id="ComponentGroupRef6" />
<ComponentGroupRef Id="ComponentGroupRef7" />
<Feature Id="f2" Display="hidden">
<ComponentRef Id="Component1" />
</Feature>
<FeatureGroupRef Id ="fg1"/>
</Feature>
</Product>
</xml>
需要在第一个Feature标签Feature id=f1之间添加一个元素。我要添加的元素格式在
下面给出<ComponentGroupRef Id="Mycomponentname" />.
生成的xml应该如下所示
<Feature Id="f1" Absent="qqq" Title="test" Level="1">
<ComponentGroupRef Id="ComponentGroupRef1" />
<ComponentGroupRef Id="ComponentGroupRef2" />
<ComponentGroupRef Id="ComponentGroupRef3" />
<ComponentGroupRef Id="ComponentGroupRef4" />
<ComponentGroupRef Id="WindowsFolder1" />
<ComponentGroupRef Id="ComponentGroupRef5" />
<ComponentGroupRef Id="ComponentGroupRef6" />
<ComponentGroupRef Id="ComponentGroupRef7" />
<ComponentGroupRef Id="Mycomponentname" />
<Feature Id="f2" Display="hidden">
<ComponentRef Id="Component1" />
</Feature>
<FeatureGroupRef Id ="fg1"/>
</Feature>
</Product>
</xml>
我尝试了下面的代码来添加元素,但它失败了
$filePath="C:'Filename.xml"
[xml]$doc=Get-Content $filePath
$x= $doc.CreateElement("ComponentGroupRef")
$x.SetAttribute('id','Mycomponentname')
$doc.Product.Feature.AppendChild($x)
我在最后一行代码中得到的错误如下
You cannot call a method on a null-valued expression.
别忘了xml标签。
$filePath="C:'Filename.xml"
[xml]$doc=Get-Content $filePath
$x= $doc.CreateElement("ComponentGroupRef", $doc.xml.Product.NamespaceURI)
$x.SetAttribute('id','Mycomponentname')
$doc.xml.Product.Feature.AppendChild($x)
需要注意的是,由于它是附加的,它将出现在fg1之后的末尾。像这样:
<xml xmlns="http://schemas.microsoft.com/wix/2006/wi">
<Product>
<Feature Id="f1" Absent="qqq" Title="test" Level="1">
<ComponentGroupRef Id="ComponentGroupRef1" />
<ComponentGroupRef Id="ComponentGroupRef2" />
<ComponentGroupRef Id="ComponentGroupRef3" />
<ComponentGroupRef Id="ComponentGroupRef4" />
<ComponentGroupRef Id="WindowsFolder1" />
<ComponentGroupRef Id="ComponentGroupRef5" />
<ComponentGroupRef Id="ComponentGroupRef6" />
<ComponentGroupRef Id="ComponentGroupRef7" />
<Feature Id="f2" Display="hidden">
<ComponentRef Id="Component1" />
</Feature>
<FeatureGroupRef Id="fg1" />
<ComponentGroupRef id="Mycomponentname" />
</Feature>
</Product>
</xml>