小编Ale*_*ail的帖子

使用PreserveWhitespace LoadOptions在XDocument中添加带有新行的新XElements

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

<root>
    <files>
        <file>a</file>

        <file>b</file>
        <file>c</file>



        <file>d</file>
    </files>
</root>
Run Code Online (Sandbox Code Playgroud)

所以我使用加载xml文档
XDocument xDoc = XDocument.Load(path, LoadOptions.PreserveWhitespace);
但是当我尝试添加新元素时,
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>
Run Code Online (Sandbox Code Playgroud)

那么如何在新行中添加新元素以节省初始格式?我试图用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 …
Run Code Online (Sandbox Code Playgroud)

c# xml whitespace linq-to-xml

6
推荐指数
2
解决办法
4104
查看次数

标签 统计

c# ×1

linq-to-xml ×1

whitespace ×1

xml ×1