我有一个像这样的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>
对于每个Item,使用PowerShell,我想创建一个只包含相关信息的xml文件。我该怎么办?
答案 0 :(得分:0)
您可以使用<Item>
获取所有SelectNodes()
个节点,然后从每个节点中选择Filename
字段SelectSingleNode()
:
$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
}
答案 1 :(得分: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")
}