Serialize XML and append new elements to XML file

巧了我就是萌 提交于 2019-12-11 11:16:53

问题


I have created a XML class using XSD2Code from my XML Schema. The class having a method SaveToFile. So when I am trying to add new elements and save it to the XML file it overwrites the entire content.

Does anyone have idea how to insert elements(append to the XML) to the XML file via Serialization.

eg:

<?xml version="1.0" encoding="utf-8"?>
<root>
  <element>content1</element>
</root>

If this is the XML file I need to add an element and the resulting should come as like below using Serialization.

<?xml version="1.0" encoding="utf-8"?>
<root>
  <element>content1</element>
  <element>content2</element>
</root>

回答1:


Your request would seem to be resolvable by adding another item into your List collection.

MyTypeFromXmlSchema myType = new MyTypeFromXmlSchema();
myType.MyElementItems = new List<MyElementItem>();
myType.MyElementItems.Add { new MyElementItem { value = "value1" } };
myType.MyElementItems.Add { new MyElementItem { value = "value2" } };

Then serialize type using XmlSerializer.



来源:https://stackoverflow.com/questions/6703782/serialize-xml-and-append-new-elements-to-xml-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!