XML(子节点序列化反序列对象)读写

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ServiceModel;
using System.Runtime.Serialization;
using System.Xml.Serialization;
using System.IO;
using System.Xml;
using System.Web;
namespace ConsoleApplication19
{
[DataContract]
public class Student
{
[DataMember]
public int? stuNo{get;set;}

[DataMember]
public string Name{get;set;}

[DataMember]
public string Sex{get;set;}
[DataMember]
public Decimal Age{get;set;}
}
class Program
{
/// <summary>
/// 在xml中获得实体配置
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static object getXmlInfo(Student obj)
{
XmlSerializer serializer = new XmlSerializer(typeof(Student));
object s;
using (MemoryStream ms = new MemoryStream())
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(("/Config/DefaultFormValue.xml"));
//xmlDoc.Load(@"C:UsersHomDocumentsvisual studio 2013ProjectsgetXmlgetXmlstudent.xml");
XmlNode tempNode = xmlDoc.SelectSingleNode("/Initialization/" + typeof(Student).Name);
if (tempNode != null)
{
XmlDocument tempDoc = new XmlDocument();
XmlDeclaration xmldecl;
xmldecl = tempDoc.CreateXmlDeclaration("1.0", "utf-8", null);
tempDoc.AppendChild(xmldecl);
XmlNode temRoot = tempDoc.CreateElement(typeof(Student).Name);
tempDoc.AppendChild(temRoot);
temRoot.InnerXml = tempNode.InnerXml;
//tempDoc.Save(@"C:UsersHomDocumentsvisual studio 2013ProjectsgetXmlgetXmlstudent1.xml");
tempDoc.Save(ms);
ms.Seek(0, SeekOrigin.Begin);
s = serializer.Deserialize(ms);
}
else
{
s = null;
}
}
return s;
}
/// <summary>
/// 在xml中写入默认配置
/// </summary>
/// <param name="obj"></param>
public static void setXmlInfo(Student obj)
{
XmlSerializer serializer = new XmlSerializer(typeof(Student));
using (MemoryStream ms = new MemoryStream())
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(("DefaultFormValue.xml"));
//xmlDoc.Load(@"C:UsersHomDocumentsvisual studio 2013ProjectsgetXmlgetXmlstudent.xml");
XmlNode tempNode = xmlDoc.SelectSingleNode("/Initialization/" + typeof(Student).Name);
if (tempNode == null)
{
serializer.Serialize(ms, obj);
XmlDocument tempDoc = new XmlDocument();
tempDoc.LoadXml(Encoding.UTF8.GetString(ms.ToArray()));
XmlElement element = xmlDoc.CreateElement(typeof(Student).Name);
element.InnerXml = tempDoc.SelectSingleNode(typeof(Student).Name).InnerXml;
XmlNode root = xmlDoc.SelectSingleNode("Initialization");
root.AppendChild(element);
xmlDoc.Save(("DefaultFormValue.xml"));
//xmlDoc.Save(@"C:UsersHomDocumentsvisual studio 2013ProjectsgetXmlgetXmlstudent.xml");
}
}
}
static void Main(string[] args)
{
Student s = new Student() { stuNo=1, Name="1",Sex="1",Age=1 };
setXmlInfo(s);
Console.ReadKey();
}
}
}

原文地址:https://www.cnblogs.com/kexb/p/4560845.html