我使用以下代码来创建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(); }
我需要动态插入节点,创建以下结构:
... David Smith ... David Smith
我该怎么做?应从键盘读取"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"), new XElement("FirstName", "David"), new XElement("LastName", "Smith")));
然后,您可以<Student>
通过搜索 - > get - > add 将更多详细信息添加到Existing
XElement particularStudent = doc.Element("School").Elements("Student") .Where(student => student.Attribute("ID").Value == "SearchID") .FirstOrDefault(); if(particularStudent != null) particularStudent.Add(new XElement("<NewElementName>","<Value>");
终于我成功了:)
if (!File.Exists("Test.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.WriteStartElement("Student"); xmlWriter.WriteElementString("FirstName", firstName); xmlWriter.WriteElementString("LastName", lastName); xmlWriter.WriteEndElement(); xmlWriter.WriteEndElement(); xmlWriter.WriteEndDocument(); xmlWriter.Flush(); xmlWriter.Close(); } } else { XDocument xDocument = XDocument.Load("Test.xml"); XElement root= xDocument.Element("School"); IEnumerable<XElement> rows = root.Descendants("Student"); XElement firstRow= rows.First(); firstRow.AddBeforeSelf( new XElement("Student", new XElement("FirstName", firstName), new XElement("LastName", lastName))); xDocument.Save("Test.xml"); }