[英]PowerShell Script to Delete XML Element
I have an XML doccument that looks like this: 我有一个XML文档,如下所示:
<Task>
<Settings>
</Settings>
<Sub>foo</Sub>
<Body>bar</Body>
</Task>
From PowerShell I can happily get the contents of 'Sub' and 'Body' using: 从PowerShell我可以愉快地使用以下内容获取'Sub'和'Body'的内容:
$Body = $XMLFile.Task.Body
But I am trying to REMOVE the 'Sub' and 'Body' Tags completely so the XML would be: 但我试图完全删除'Sub'和'Body'标签,因此XML将是:
<Task>
<Settings>
</Settings>
</Task>
I have already Tried many things, Including: 我已经尝试了很多东西,包括:
.RemoveChild()
method (Threw an exeption relating to Object reference) .RemoveChild()
方法( .RemoveChild()
与Object引用相关的exeption) Even opening the file as a text file and trying: 甚至将文件作为文本文件打开并尝试:
Get-Content $_.FullName -notmatch "<Sub>" | out-file $_.FullName
^^ This does nothing at all ^^这什么都不做
Also for this application of script I would be unable to use any third party modules 此外,对于此脚本应用程序,我将无法使用任何第三方模块
You can use Where-Object
to find the Child nodes you want to remove and then call RemoveChild()
: 您可以使用
Where-Object
查找要删除的子节点,然后调用RemoveChild()
:
$Input = "C:\path\task.xml"
$Output = "C:\path\newtask.xml"
# Load the existing document
$Doc = [xml](Get-Content $Input)
# Specify tag names to delete and then find them
$DeleteNames = "Sub","Body"
($Doc.Task.ChildNodes |Where-Object { $DeleteNames -contains $_.Name }) | ForEach-Object {
# Remove each node from its parent
[void]$_.ParentNode.RemoveChild($_)
}
# Save the modified document
$Doc.Save($Output)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.