Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/solr/3.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# 将节点追加到XML文件_C# - Fatal编程技术网

C# 将节点追加到XML文件

C# 将节点追加到XML文件,c#,C#,我有一个包含学校元素的XML文件 <Classrooms> <Classroom ID="Mrs.S"> <Students> <Student> <Name> Billy Blue </Name> <Grade> 1 </Grade> <Sex> Male </Sex> <Age> 7 </Age&

我有一个包含学校元素的XML文件

 <Classrooms>
  <Classroom ID="Mrs.S">
   <Students>
    <Student>
     <Name> Billy Blue </Name>
     <Grade> 1 </Grade>
     <Sex> Male </Sex>
     <Age> 7 </Age>
     <Picture> c:/School/Students/BillyBlue </Picture>
   </Student>
  </Students>
 </Classroom>
</Classrooms>
您可以找到“学生”节点

最后,您可以将新节点附加到此节点

node.AppendChild(student);
//xmlDoc.DocumentElement.AppendChild(student);
xmlDoc.Save(ConfigurationManager.AppSettings.Get("studentFile"));

使用
LinqtoXml
,这相当容易做到。强烈建议使用:

然后,您可以执行不同的操作,例如排序:

IEnumerable<decimal> names =  
    from student in root.Elements("Students")  
    orderby student.Name  
    select student.Name;  
foreach (string name in names)  
    Console.WriteLine(name);  
IEnumerable名称=
来自根元素中的学生(“学生”)
学生订购。姓名
选择学生姓名;
foreach(名称中的字符串名称)
Console.WriteLine(名称);
您需要找到“Student”元素,然后将“Student”元素附加到其中。
node.AppendChild(student);
//xmlDoc.DocumentElement.AppendChild(student);
xmlDoc.Save(ConfigurationManager.AppSettings.Get("studentFile"));
try
{
    XDocument xmlDoc = XDocument.Load("StudentDoc.xml"));
    xmlDoc.Element("Students").Add(
    new XElement("Student", 
    new XElement("Name", "Peter"),
    new XElement("Grade", 10.0), 
    new XElement("Sex", "Male")));

    xmlDoc.Save("StudentDoc.xml"));
}
catch{}
IEnumerable<decimal> names =  
    from student in root.Elements("Students")  
    orderby student.Name  
    select student.Name;  
foreach (string name in names)  
    Console.WriteLine(name);