我使用以下代码来创建
XML文件:
XmlWriterSettings xmlWriterSettings = new XmlWriterSettings(); xmlWriterSettings.Indent = true; xmlWriterSettings.NewLineOnAttributes = true; using (XmlWriter xmlWriter = XmlWriter.Create("Test.xml",xmlWriterSettings)) { xmlWriter.WriteStartDocument(); xmlWriter.WriteStartElement("School"); xmlWriter.WriteEndElement(); xmlWriter.WriteEndDocument(); xmlWriter.Close(); }
我需要动态插入节点,创建以下结构:
<?xml version="1.0" encoding="utf-8"?> <School /> <Student> <FirstName>David</FirstName> <LastName>Smith</LastName> </Student> ... <Teacher> <FirstName>David</FirstName> <LastName>Smith</LastName> </Teacher> ... </School>
我该怎么做?应从键盘读取“FirstName”和“LastName”的值,并且可以随时输入值,当然在现有值下.
解决方法
你可以使用Linq Xml
XDocument doc = XDocument.Load(xmlFilePath); XElement school = doc.Element("School"); school.Add(new XElement("Student",new XElement("FirstName","David"),new XElement("LastName","Smith"))); doc.Save(xmlFilePath);
编辑
如果要将Element添加到Existing< Student>,只需添加一个Attribute
school.add(new XElement("Student",new XAttribute("ID","ID_Value"),"Smith")));
然后,您可以向现有< Student>添加更多详细信息.通过搜索 – >得到 – >加
XElement particularStudent = doc.Element("School").Elements("Student") .Where(student => student.Attribute("ID").Value == "SearchID") .FirstOrDefault(); if(particularStudent != null) particularStudent.Add(new XElement("<NEwElementName>","<Value>");