2016-01-29 108 views
-1

我有一個XML文件是這樣的:
創建子XML文件?

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?> 
<Item> 
<Field Name="Filename">x1</Field> 
<Field Name="Year">y1</Field> 
<Field Name="Name">z1</Field> 
</Item> 
<Item> 
<Field Name="Filename">xn</Field> 
<Field Name="Year">yn</Field> 
<Field Name="Name">zn</Field> 
</Item> 

對於每一個項目,使用PowerShell的,我想創建一個XML文件,只有與它有關的信息。我該怎麼做?

+0

是否有您試圖偶爾做這件事?我們想幫助改進您的代碼。 – Matt

+0

您是否期望您的輸出也是XML(標題?) – Matt

+0

是的。使用xml標頭 – 8139david

回答

0

你可以抓住所有<Item>節點與SelectNodes(),然後從每一個選擇FilenameSelectSingleNode()

$xml = [xml]@' 
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?> 
<Items> 
<Item> 
<Field Name="Filename">x1</Field> 
<Field Name="Year">y1</Field> 
<Field Name="Name">z1</Field> 
</Item> 
<Item> 
<Field Name="Filename">xn</Field> 
<Field Name="Year">yn</Field> 
<Field Name="Name">zn</Field> 
</Item> 
</Items> 
'@ 

foreach($item in $xml.SelectNodes('//Item')) 
{ 
    $Filename = $item.SelectSingleNode('//Field[@Name = "Filename"]').InnerText 

    # create your new xml document here, import $Item and save to $Filename 
} 
+0

非常感謝,我會盡力的! – 8139david

0

你可以嘗試這樣的事:

$xml = [xml]@' 
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?> 
<Items> 
<Item> 
<Field Name="Filename">x1</Field> 
<Field Name="Year">y1</Field> 
<Field Name="Name">z1</Field> 
</Item> 
<Item> 
<Field Name="Filename">xn</Field> 
<Field Name="Year">yn</Field> 
<Field Name="Name">zn</Field> 
</Item> 
</Items> 
'@ 

$xml.Items.Item | ForEach-Object { 
    $filename = $_.SelectSingleNode("Field[@Name='Filename']").innertext 
    $file = New-Object xml 
    $file.InsertBefore($file.CreateXmlDeclaration("1.0","UTF-8","yes"),$file.DocumentElement) | Out-Null 
    $file.AppendChild($file.ImportNode($_,$true)) | Out-Null 
    $file.Save("C:\users\frode\Desktop\$($filename).xml") 
}