如何提取 XML 的节点并创建新的 XML 文档 [英] How to extract a node of XML and create a new XML document

查看:53
本文介绍了如何提取 XML 的节点并创建新的 XML 文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用 Powershell 从较大的 XML 文档中提取一个节点(和子节点),并创建一个新的独立 XML 文档,该文档仅包含提取的 XML 节点(和子节点);然后我需要将这个新提取的 XML 保存在一个文件中.被提取的顶级 XML 节点具有属性.看来我必须设置新 XML 对象的 XMLDocument 值才能执行此操作,但 XMLDocument 是只读属性.有人可以帮忙吗?

I need to use Powershell to extract a node (and children) from a larger XML document and create a new standalone XML document containing only the extracted XML node (and children); then I need to save this new extracted XML in a file. The top-level XML node being extracted has attributes. It appears that I will have to set the new XML object's XMLDocument value to do this, but XMLDocument is a read-only property. Can anyone help?

推荐答案

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

The crux is to use the XmlDocument.ImportNode() method e.g.:

$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")

这篇关于如何提取 XML 的节点并创建新的 XML 文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆