2016-01-29 76 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") 
}