使用XmlWriter附加现有的XML文件
我已经使用下面的代码来创build一个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(); }
我需要dynamic插入节点创build以下结构:
<?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”的值,当然可以在任何时候input值。
你可以使用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);
编辑
如果你想添加元素到现有的<Student>
,只需添加一个属性
school.add(new XElement("Student", new XAttribute("ID", "ID_Value"), new XElement("FirstName", "David"), new XElement("LastName", "Smith")));
然后,您可以通过search – >获取 – >添加将更多的详细信息添加到现有的<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>");
最后我成功了:)
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"); }
让我给你一个build议。 当你创build你的xml文件时,给你的学生一个唯一的id,像这样:
// to store the id variable, if you create more than one student you can increase it count = 0; xmlWriter.WriteStartElement("School"); xmlWriter.WriteAttributeString("ID",count.ToString()); xmlWriter.WriteEndElement();
然后,当你需要添加信息给这个学生时,你可以得到ID
, Firstname
和Firstname
,你可以像这样用LINQ to XML来编辑你的XML文件:
int id = Convert.ToInt32(txtStudentId.Text); XDocument xDoc = XDocument.Load("Test.xml"); XElement student = xDoc.Descendants("Student").Where(x => (string) x.Attribute("ID") == id).FirstOrDefault(); if (student != null) { string firstName = txtFirstName.Text; string lastName = txtLastName.Text; XElement first = new XElement("FirstName", firstName); XElement last = new XElement("LastName", lastName); student.Add(first); student.Add(last); xDoc.Save("Test.xml"); }
我知道你问XmlWriter,但我相信你可以用XDocument使用较less的代码来实现这一点。 这是我的解决scheme:
var filePath = "path/XmlFile.xml"; var xmlDoc = XDocument.Load(filePath); var parentElement = new XElement("Student"); var firstNameElement = new XElement("FirstName", firstNameVariable); var lastNameElement = new XElement("LastName", lastNameVariable); parentElement.Add(firstNameElement); parentElement.Add(lastNameElement); var rootElement = xmlDoc.Element("School"); rootElement?.Add(parentElement); xmlDoc.save();
这是基于下面的XML结构,将附加在...
:
<School> <Student> <FirstName>John</FirstName> <LastName>Johnson</LastName> </Student> ... </School>
希望这可以帮助!
我下次有个build议:
string nameFile = "Test.xml"; bool newFile = false; if (!File.Exists(nameFile)) { newFile = true; XmlWriterSettings xmlWriterSettings = new XmlWriterSettings(); xmlWriterSettings.Indent = true; xmlWriterSettings.NewLineOnAttributes = true; xmlWriter.WriteStartDocument(); xmlWriter.WriteStartElement("School"); xmlWriter = XmlWriter.Create("Test.xml", xmlWriterSettings)) } else { doc = new XmlDocument(); doc.Load(nameFile); // Create a XPathNavigator // You can go where you want to add // In this case it is just after last child of the roor XPathNavigator navigator = doc.CreateNavigator(); navigator.MoveToChild("School", ""); xmlWriter = navigator.AppendChild(); } // From here you can work only with xmlWriter, // One will point on a file and the other on the stream of xmlDocument // So you will need to save the document in the second choise xmlWriter.WriteStartElement("Student"); xmlWriter.WriteElementString("FirstName", firstName); xmlWriter.WriteElementString("LastName", lastName); xmlWriter.WriteEndElement(); // End document / close or save. if (newFile) xmlWriter.WriteEndDocument(); xmlWriter.Close(); if (!newFile) doc.Save(nameFile);
它应该工作。 🙂