使用XmlWriter附加现有XML文件

时间:2014-01-04 15:29:16

标签: c# xml xmlreader xmlwriter

我使用以下代码创建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”的值,并且可以随时输入值,当然也可以在现有值下输入。

5 个答案:

答案 0 :(得分:19)

你可以使用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")));

然后,您可以通过搜索将更多详细信息添加到现有<Student> - &gt;得到 - &gt;添加

XElement particularStudent = doc.Element("School").Elements("Student")
                                .Where(student => student.Attribute("ID").Value == "SearchID")
                                .FirstOrDefault();
if(particularStudent != null)
    particularStudent.Add(new XElement("<NEwElementName>","<Value>");

答案 1 :(得分:12)

最后我成功了:)

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");
}

答案 2 :(得分:2)

我给你一个建议。在创建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();

然后,当您需要向此学生添加信息时,您可以获得IDFirstnameLastname,并且您可以使用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");
}

答案 3 :(得分:1)

我有下一次的建议:

private void CallService_1_Click(object sender, EventArgs e)
        {
            try
            {

                string _uri = "net.tcp://localhost/NetTcptest/Service1.svc/mex";
                NetTcpBinding binding = new NetTcpBinding();
                binding.Security.Mode = SecurityMode.None;
                binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.None;
                binding.Security.Transport.ProtectionLevel = System.Net.Security.ProtectionLevel.None;
                binding.Security.Message.ClientCredentialType = MessageCredentialType.None;
                EndpointAddress address = new EndpointAddress(_uri);
                ChannelFactory<IService1> channel = new ChannelFactory<IService1>(binding, address);
                IService1 clientProxy = channel.CreateChannel();
                label1.Text = clientProxy.GetData(100);


            }
            catch (Exception ex)
            {
                label1.Text = ex.Message;
            }
        }

它应该工作。 :)

答案 4 :(得分:1)

我知道您要求使用XmlWriter,但我相信您可以使用XDocument使用更少的代码来实现此目的。这是我的解决方案:

...

这基于以下XML结构,并将附加在<School> <Student> <FirstName>John</FirstName> <LastName>Johnson</LastName> </Student> ... </School>

lappend data {*}$fr

希望这有帮助!