在 XDocument 中使用保留空白加载选项添加新的 XElement

本文关键字:添加 选项 XElement 加载 空白 XDocument 保留 | 更新日期: 2023-09-27 18:34:33

我正在尝试编辑XML文件保存其格式:

<root>
    <files>
        <file>a</file>
        <file>b</file>
        <file>c</file>

        <file>d</file>
    </files>
</root>

所以我使用 XDocument xDoc = XDocument.Load(path, LoadOptions.PreserveWhitespace); 加载 xml 文档

但是当我尝试添加新元素时
xDoc.Root.Element("files").Add(new XElement("test","test")); xDoc.Root.Element("files").Add(new XElement("test2","test2"));
它在同一行中添加,因此输出如下所示:

<root>
    <files>
        <file>a</file>
        <file>b</file>
        <file>c</file>

        <file>d</file>
    <test>test</test><test2>test2</test2></files>
</root>

那么如何在新行上添加新元素以保存初始格式呢?我尝试将XmlWriterSetting.Indent = true一起使用来保存 XDocument,但如我所见,当我使用 xDoc.Root.Element().Add()

更新:程序加载,修改和保存文档的完整部分

using System;
using System.Xml;
using System.Xml.Linq;
using System.Text;
namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {            
            string path = @".'doc.xml";    
            XDocument xDoc = XDocument.Load(path, LoadOptions.PreserveWhitespace);
            //when i debug i see in "watch" that after these commands new elements are already added in same line
            xDoc.Descendants("files").First().Add(new XElement("test", "test"));
            xDoc.Descendants("files").First().Add(new XElement("test2", "test2"));
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Encoding = Encoding.UTF8;
            settings.Indent = true;
            settings.IndentChars = "'t";
            using (XmlWriter writer = XmlTextWriter.Create(path, settings))
            {                
                xDoc.Save(writer);
                //Here i also tried save without writer - xDoc.Save(path)
            }
        }
    }
}

在 XDocument 中使用保留空白加载选项添加新的 XElement

问题似乎是由您使用LoadOptions.PreserveWhitespace引起的。这似乎胜过XmlWriterSettings.Indent - 你基本上已经说过,"我关心这个空白"......"哦,现在我没有了。">

如果删除该选项,只需使用:

XDocument xDoc = XDocument.Load(path);

。然后它适当地缩进。如果您想保留所有原始空格,但只缩进新元素,我认为您需要自己添加该缩进。

我有一个类似的问题,我可以用下面的代码解决:

var newPolygon = new XElement(doc.Root.GetDefaultNamespace() + "polygon");
groupElement.Add(newPolygon); 
groupElement.Add(Environment.NewLine); 

我希望这段代码可以帮助一些人...

相关文章: