Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/336.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用C在XML文件中的Xelement之前添加格式化空间#_C#_Xml_Linq To Xml_Xdoc - Fatal编程技术网

C# 使用C在XML文件中的Xelement之前添加格式化空间#

C# 使用C在XML文件中的Xelement之前添加格式化空间#,c#,xml,linq-to-xml,xdoc,C#,Xml,Linq To Xml,Xdoc,我试图向XML文件中添加一个XElement,其中元素已经以特定格式存在(请参见第2行,其中Student元素前面有空格),但是当我添加XElement时,如何在XElement之前添加空格?有关格式化空间的差异,请参见下图第5行。 在此处创建标记: XElement newStudent = new XElement("Student"); newStudent.SetAttributeValue("Name", "jhonny

我试图向XML文件中添加一个XElement,其中元素已经以特定格式存在(请参见第2行,其中Student元素前面有空格),但是当我添加XElement时,如何在XElement之前添加空格?有关格式化空间的差异,请参见下图第5行。

在此处创建标记:

    XElement newStudent = new XElement("Student");
    newStudent.SetAttributeValue("Name", "jhonny");
    newStudent.Add(new XText("\n        "));


    XElement stuSetting = new XElement("Subject");
    stuSetting.SetAttributeValue("Name", "C#");
    stuSetting.SetAttributeValue("Mark", "95");

    newStudent.Add(stuSetting);
    newStudent.Add(new XText("\n  "));
通过使用XDocument加载现有文件来添加该文件:

        StudentsXmlFile.Element("Students").Add(newStudent);
        StudentsXmlFile.Element("Students").Add(new XText("\n"));
必填项:

当前正在获取输出:


不要添加您自己的退货'\n'。它会自动添加到XDocument中。返回值造成了缩进问题。@jdweng:如果我不放\n,它会在一行中创建xml元素。您添加的属性总是与标记在同一行。您发布的代码与您发布的图片不一致。请尝试SetValue而不是SetAttributeValue。