如何解决使用PowerShell找到并选择两个文件之间的xml属性
| 我有两个xml文件。 File1.xml:<fileAsset fileAssetGuid=\"guid1\" assetTitle=\"Title1\" />
<fileAsset fileAssetGuid=\"guid2\" assetTitle=\"Title2\" />
<fileAsset fileAssetGuid=\"guid3\" assetTitle=\"Title3\" />
File2.xml:
<file id=\"guid1\" />
<file id=\"guid2\" />
<file id=\"guid3\" />
我知道File1.xml(\“ Title1 \”)中assetTitle的值。我需要使用该值来获取/选择file1.xml中的fileAssetGuid(\“ guid1 \”)值。然后,我需要使用file1.xml中fileAssetGuid的值(\“ guid1 \”)来找到file2.xml中的ID(\“ guid1 \”)。
如何在PowerShell中完成此操作?
解决方法
跟进斯特伊的建议。
Select-Xml -Path \"$pwd\\file1.xml\" -XPath \"/root/fileAsset[@assetTitle]\" |
ForEach {
$id = $_.Node.fileAssetGuid
Select-Xml -Path \"$pwd\\file2.xml\" -XPath \"/root/file[@id=\'$id\']\" |
ForEach { $_.Node }
}
############
############
foreach( $assetGuideRecord in (Select-Xml -Path \"$pwd\\file1.xml\" -XPath \"/root/fileAsset[@assetTitle]\") ) {
$id = $assetGuideRecord.node.fileAssetGuid
foreach( $record in (Select-Xml -Path \"$pwd\\file2.xml\" -XPath \"/root/file[@id=\'$id\']\") ) {
$record.node
}
}
, 以下应该做您想做的(出于说明目的,我添加了一些内容):
PS D:\\MiLu\\Dev\\PowerShell> cat .\\xmlsel1.xml
<file1>
<fileAsset fileAssetGuid=\"guid1\" assetTitle=\"Title1\" />
<fileAsset fileAssetGuid=\"guid2\" assetTitle=\"Title2\" />
<fileAsset fileAssetGuid=\"guid3\" assetTitle=\"Title3\" />
</file1>
PS D:\\MiLu\\Dev\\PowerShell> cat .\\xmlsel2.xml
<file2>
<file id=\"guid1\" data=\"one\" />
<file id=\"guid2\" data=\"two\" />
<file id=\"guid3\" data=\"three\" />
</file2>
PS D:\\MiLu\\Dev\\PowerShell> cat .\\xmlsel.ps1
$doc1 = [xml](get-content xmlsel1.xml)
$title = \"Title2\"
$asset = $doc1.file1.fileAsset | where { $_.assetTitle -eq $title }
# echo $asset
# echo $asset.assetTitle
# echo $asset.fileAssetGuid
$doc2 = [xml](get-content xmlsel2.xml)
$file = $doc2.file2.file | where { $_.id -eq $asset.fileAssetGuid }
# echo $file
echo $file.data
PS D:\\MiLu\\Dev\\PowerShell> .\\xmlsel.ps1
two
, 使用Xpath。
# Load up the XML 1. I\'ve used here-string,but anything goes.
[xml]$x1 = @\'
<root>
<fileAsset fileAssetGuid=\"guid1\" assetTitle=\"Title1\" />
<fileAsset fileAssetGuid=\"guid2\" assetTitle=\"Title2\" />
<fileAsset fileAssetGuid=\"guid3\" assetTitle=\"Title3\" />
</root>
\'@
# Ditto for XML 2.
[xml]$x2 = @\'
<root>
<file id=\"guid1\" />
<file id=\"guid2\" />
<file id=\"guid3\" />
</root>
\'@
# Look for fileAsset element that has assettitle attribute
# which has value Title1
$n=$x1.SelectSinglenode(\"/root/fileAsset[@assetTitle=\'Title1\']\")
# Look for file node from XML2 that has id attribute
# that has value we got from XML1 with assetTitle
$x2.SelectSingleNode(\"/root/file[@id=`\"$($n.fileAssetGuid)`\"]\")
# Remove the node by calling its parent\'s RemoveChild()
$n2.ParentNode.RemoveChild($n2)
# View final XML on the console
$x2.Save([console]::out)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。