我有一个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>
需要在第一个功能标记功能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.
答案 0 :(得分:1)
不要忘记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>