加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 使用PreserveWhitespace LoadOptions在XDocument中添加带

发布时间:2020-12-15 18:12:58 所属栏目:百科 来源:网络整理
导读:我正在尝试编辑保存其格式的 XML文件: root files filea/file fileb/file filec/file filed/file /files/root 所以我使用XDocument xDoc = XDocument.Load(path,LoadOptions.PreserveWhitespace)加载xml文档; 但是当我试图添加新元素xDoc.Root.Element(“fi
我正在尝试编辑保存其格式的 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”)时.添加(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>

那么如何在新行中添加新元素以节省初始格式?我尝试使用带有Setting.Indent = true的XmlWriter来保存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)
            }
        }
    }
}

解决方法

问题似乎是由您使用LoadOptions.PreserveWhitespace引起的.这似乎胜过XmlWriterSettings.Indent – 你基本上说过,“我关心这个空白”……“哦,现在我没有.”

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

XDocument xDoc = XDocument.Load(path);

…然后适当地缩进.如果你想保留所有原始空格,但只是缩进新元素,我想你需要自己添加缩进.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读