Kei*_*ith 4 powershell insertafter
我有一些xml文件,我想将一个xml文件的内容插入另一个.我以为我会使用LastChild和InsertAfter方法来完成此任务.到目前为止它对我不起作用.
这是parent.xml文件:
<manifest>
<manifestExecution>
<assetDetail>
<fileAsset fileAssetGuid="parentguid1">
<parentfile1 />
</fileAsset>
<fileAsset fileAssetGuid="parentguid2">
<parentfile2 />
</fileAsset>
</assetDetail>
</manifestExecution>
</manifest>
Run Code Online (Sandbox Code Playgroud)
这是child.xml文件:
<manifest>
<manifestExecution>
<assetDetail>
<fileAsset fileAssetGuid="childguid1">
<childfile1 />
</fileAsset>
</assetDetail>
</manifestExecution>
</manifest>
Run Code Online (Sandbox Code Playgroud)
我想要做的是从child.xml中选择fileAsset节点,并在parent.xml中的最后一个fileAsset节点之后插入parent.xml.
这是我的测试代码:
$parent = [xml] (Get-Content d:\temp\parent.xml)
$parentnode = $parent.manifest.manifestExecution.assetDetail
$child = [xml] (Get-Content d:\temp\child.xml)
$childnode = $child.manifest.manifestExecution.assetDetail.InnerXml
$parentnode.InsertAfter($childnode, $parentnode.LastChild)
Run Code Online (Sandbox Code Playgroud)
这是我得到的错误信息:
Cannot convert argument "0", with value: "<fileAsset fileAssetGuid="childguid1"> <childfile1 /></fileAsset>", for "InsertAfter" to type "System.Xml.XmlNode": "Cannot conver
t the "<fileAsset fileAssetGuid="childguid1"><childfile1 /></fileAsset>" value of type "System.String" to type "System.Xml.XmlNode"."
At line:5 char:24
+ $parentnode.InsertAfter <<<< ($childnode, $parentnode.LastChild)
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument
我究竟做错了什么?
您需要遍历$childnode子项,从父项中删除它们,然后在追加之前将它们导入新文档上下文($child并且$parent是不同的XmlDocument实例)$parentnode.
这将追加所有fileAsset从节点$childnode到$parentnode.
$parent = [xml](get-content d:\temp\parent.xml)
$parentnode = $parent.manifest.manifestexecution.assetdetail
$child = [xml](get-content d:\temp\child.xml)
$childnode = $child.manifest.manifestexecution.assetdetail
while ($childnode.haschildnodes) {
$cn = $childnode.firstchild
$cn = $childnode.removechild($cn)
$cn = $parentnode.ownerdocument.importnode($cn, $true)
$parentnode.appendchild($cn)
}
Run Code Online (Sandbox Code Playgroud)
幸运的是,大多数这些方法返回相同XmlNode或新版本的方法,因此while循环体可以链接在一起,如下所示:
$parentnode.appendchild( $parentnode.ownerdocument.importnode( $childnode.removechild( $childnode.firstchild ), $true ))
Run Code Online (Sandbox Code Playgroud)
InsertAfter(newChild,referenceChild) 也可以工作,但会有所不同,因为它还需要引用它之后插入的节点.
| 归档时间: |
|
| 查看次数: |
6991 次 |
| 最近记录: |