使用PowerShell查找并选择两个文件之间的xml属性

时间:2011-06-10 05:18:32

标签: xml powershell

我有两个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中完成此操作?

3 个答案:

答案 0 :(得分:2)

以下内容应该做你想要的(我为了说明目的添加了东西):

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

答案 1 :(得分:2)

使用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)

答案 2 :(得分:1)

跟进stej的建议。

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
    }
}