当元素为空时,保存将返回换行符添加到 XML [英] Save adds return linebreaks to XML when elements are blank
问题描述
我正在加载一个 XML 文档,其中有一些没有内部文本的标签.
I'm loading a XML Document that has some tags that have no innertext.
如果我用一些数据填充内部文本,那么它会根据需要工作(您将开始标记、内部文本和结束标记都放在一行中),如下所示...
If I populate the innertext with some data then it works as needed (you get opening tag, innertext and closing tag all on one line) like the following...
<element>value</element>
问题出现在没有值的标签上.这些应该以与上面相同的方式显示,当然,除了没有值,如下所示:
The problem arises with tags with no values. These SHOULD be displayed in the same way as above with the exception of no value of course, like the following:
<element></element>
然而,当内部文本有一个空字符串时,它会添加一个回车符 &不是预期的换行符!它最终看起来像下面这样:
However, when the innertext has an empty string it adds a carriage return & line feed which is not what is expected! It ends up looking like the following:
<element>
</element>
我的代码:
$input_dir = "F:\uma\zz"
$output_dir = "F:\uma\zz"
[xml]$xdoc = Get-Content "$input_dir\Subnet_Network_41.xml"
$inprange = 5
foreach ($i in $inprange) {
$xdoc.Subnet.Id = "Network_$i"
$xdoc.Subnet.Name = "Network_$i"
$xdoc.Save("$output_dir\Subnet_Network_$i.xml")
}
推荐答案
我自己解决了这个问题.我已经使用 Select-xml
来读取 xml 文件并且它起作用了.它在保存 xml 文档时没有添加返回换行符.下面是工作代码.
I have fixed the issue myself. I have used Select-xml
to read the xml file and it worked. It didnt add the return linebreaks while saving the xml document. below is the working code.
$input_dir = "F:\uma\zz"
$output_dir = "F:\uma\zz"
$xdoc = ( Select-Xml -Path $input_dir\Subnet_Network_41.xml -XPath / ).Node
$inprange = 5
foreach ($i in $inprange) {
$xdoc.Subnet.Id = "Network_$i"
$xdoc.Subnet.Name = "Network_$i"
$xdoc.Save("$output_dir\Subnet_Network_$i.xml")
}
要了解有关 Select-xml
的更多信息,请参阅以下博客:https://blog.stangroome.com/2014/02/10/powershell-select-xml-versus-get-content/
To know more about Select-xml
refer the below blog: https://blog.stangroome.com/2014/02/10/powershell-select-xml-versus-get-content/
这篇关于当元素为空时,保存将返回换行符添加到 XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!