Powershell 保存 XML 并保留格式 [英] Powershell saving XML and preserving format

查看:74
本文介绍了Powershell 保存 XML 并保留格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想读入一个 XML 文件并修改一个元素,然后将其保存回文件.在保留格式并保持匹配行终止符(CRLF 与 LF)的同时执行此操作的最佳方法是什么?

这是我所拥有的,但它没有这样做:

$xml = [xml]([System.IO.File]::ReadAllText($fileName))$xml.PreserveWhitespace = $true# 改变一些元素$xml.Save($fileName)

问题是在我混合了 LF 和 CRLF 之后,额外的新行(也就是 xml 中的空行)被删除了.

解决方案

您可以使用 PowerShell [xml] 对象并设置 $xml.PreserveWhitespace = $true,或者使用 .NET XmlDocument:

$f = '.\xml_test.xml'# 使用 .NET XmlDocument$xml = 新对象 System.Xml.XmlDocument$xml.PreserveWhitespace = $true# 或者使用 PS [xml] (旧的 PowerShell 版本可能需要使用 psbase)$xml = 新对象 xml#$xml.psbase.PreserveWhitespace = $true # 较旧的 PS 版本$xml.PreserveWhitespace = $true# 使用保留设置加载$xml.Load($f)$n = $xml.SelectSingleNode('//文件')$n.InnerText = 'b'$xml.Save($f)

只需确保设置 PreserveWhitespace在调用 XmlDocument.Load 或 XmlDocument.LoadXml 之前.

注意:这不会保留 XML 属性之间的空白!空格 in XML 属性似乎被保留,但不是 之间.该文档讨论了保留空白节点"(node.NodeType = System.Xml.XmlNodeType.Whitespace)而不是属性.>

I want to read in an XML file and modify an element then save it back to the file. What is the best way to do this while preserving the format and also keep matching Line terminator (CRLF vs LF)?

Here is what I have but it doesn't do that:

$xml = [xml]([System.IO.File]::ReadAllText($fileName))
$xml.PreserveWhitespace = $true
# Change some element
$xml.Save($fileName)

The problem is that extra new lines (aka empty lines in the xml) are removed and after I have mixed LF and CRLF.

解决方案

You can use the PowerShell [xml] object and set $xml.PreserveWhitespace = $true, or do the same thing using .NET XmlDocument:

$f = '.\xml_test.xml'

# Using .NET XmlDocument
$xml = New-Object System.Xml.XmlDocument
$xml.PreserveWhitespace = $true

# Or using PS [xml] (older PowerShell versions may need to use psbase)
$xml = New-Object xml
#$xml.psbase.PreserveWhitespace = $true  # Older PS versions
$xml.PreserveWhitespace = $true

# Load with preserve setting
$xml.Load($f)
$n = $xml.SelectSingleNode('//file')
$n.InnerText = 'b'
$xml.Save($f)

Just make sure to set PreserveWhitespace before calling XmlDocument.Load or XmlDocument.LoadXml.

NOTE: This does not preserve white space between XML attributes! White space in XML attributes seem to be preserved, but not between. The documentation talks about preserving "white space nodes" (node.NodeType = System.Xml.XmlNodeType.Whitespace) and not attributes.

这篇关于Powershell 保存 XML 并保留格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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