如何提取XML节点并创建新的XML文档

如何提取XML节点并创建新的XML文档,xml,powershell,xmldocument,Xml,Powershell,Xmldocument,我需要使用Powershell从更大的XML文档中提取节点和子节点,并创建一个新的独立XML文档,其中只包含提取的XML节点和子节点;然后我需要将这个新提取的XML保存到一个文件中。正在提取的顶级XML节点具有属性。似乎我必须设置新XML对象的XMLDocument值才能做到这一点,但XMLDocument是只读属性。有人能帮忙吗?关键是使用XmlDocument.ImportNode方法,例如: $xml1 = [xml](Get-Content foo.xml) # find the nod

我需要使用Powershell从更大的XML文档中提取节点和子节点,并创建一个新的独立XML文档,其中只包含提取的XML节点和子节点;然后我需要将这个新提取的XML保存到一个文件中。正在提取的顶级XML节点具有属性。似乎我必须设置新XML对象的XMLDocument值才能做到这一点,但XMLDocument是只读属性。有人能帮忙吗?

关键是使用XmlDocument.ImportNode方法,例如:

$xml1 = [xml](Get-Content foo.xml)
# find the node you want to extract
$node = $xml1.Foo.Bar

$xml2 = New-Object System.Xml.XmlDocument
$newNode = $xml2.ImportNode($node, $true)
$xml2.AppendChild($newNode)
$xml2.Save("bar.xml")
关键是使用XmlDocument.ImportNode方法,例如:

$xml1 = [xml](Get-Content foo.xml)
# find the node you want to extract
$node = $xml1.Foo.Bar

$xml2 = New-Object System.Xml.XmlDocument
$newNode = $xml2.ImportNode($node, $true)
$xml2.AppendChild($newNode)
$xml2.Save("bar.xml")

非常感谢。我在其他任何地方都没有找到如此简洁正确的答案。谢谢。我在其他任何地方都没有找到如此简洁正确的答案。