当元素为空时,XMLDocument.Save将返回载体添加到XML
我正在加载一个XML文档,其中包含一些没有innertext的标记。
如果我用一些数据填充innertext,那么它可以根据需要工作(你可以在一行上打开标签,innertext和关闭标签),如下所示……
value
问题出现在没有值的标签上。 这些应该以与上面相同的方式显示,除了没有粗略值,例如以下……
但是,当innertext有一个空字符串时,它会添加一个回车和换行符,这不是预期的! 最终看起来像以下……
这是我目前的代码,产生上述结果……
XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(@"C:\test.xml"); //Save the xml and then cleanup xmlDoc.Save(@"C:\test.xml");
这为我修好了……
XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(@"C:\test.xml"); //Save the xml and then cleanup XmlWriterSettings settings = new XmlWriterSettings { Indent = true }; XmlWriter writer = XmlWriter.Create(@"C:\test.xml", settings); xmlDoc.Save(writer);
您可以通过Settings Property中的XMLWriter来控制它。
查看此示例以及以下参考。 http://msdn.microsoft.com/en-us/library/ms162618.aspx
请参阅http://msdn.microsoft.com/en-us/library/system.xml.xmlwriter.aspx http://msdn.microsoft.com/en-us/library/system.xml.xmlwritersettings.aspx http:/ /msdn.microsoft.com/en-us/library/system.xml.xmlwritersettings.newlinehandling.aspx
可能为时已晚,但我提到了Arvo Bowen给出的解决方案。 Arvo的解决方案是在C#中,我在Powershell语法中写了相同的内容
# $dest_file is the path to the destination file $xml_dest = [XML] (Get-Content $dest_file) # # Operations done on $xml_dest # $settings = new-object System.Xml.XmlWriterSettings $settings.CloseOutput = $true $settings.Indent = $true $writer = [System.Xml.XmlWriter]::Create($dest_file, $settings) $xml_dest.Save($writer) $writer.Close()
它解决了我的两个问题:
- 一,上述问题,即将换行符添加到空值/空值。
- 其次,没有为null / empty值创建结束标记。 例如:
实际上将在文件中写为$null
请参阅此主题: 我们是否可以强制XmlWriter发出my-tag>而不是 ?