C#解析XML文件

2021-05-12 10:28

阅读:452

标签:get   反序   path   pen   ref   sch   summary   反序列化   部分   

想实现:C#读取XML文件内的内容至List

 

XML文件:AppAttr.xml  其中,一定是要ArrayOfAppAttr(红色部分AppAttr为你的实体类名)

xml version="1.0" encoding="utf-8" ?>
ArrayOfAppAttr  xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

  AppAttr>
    Key>FileFolderKey>
    Value>C:/PWFileVersionValue>
  AppAttr>

  AppAttr>
    Key>CallAddressKey>
    Value>pwfileversion://Value>
  AppAttr>

ArrayOfAppAttr>

 

实体类文件:AppAttr

[Serializable]//不能忘记
public class AppAttr
{
    public AppAttr() { }
    public AppAttr(string K, string V)
    {
        Key = K;
        Value = V;
    }
    public string Key;
    public string Value;
}

 

序列化类:XmlSerialize

技术分享技术分享
class XmlSerialize
{
    ///   
    /// 反序列化XML为类实例  
    ///   
    ///   
    ///   
    ///   
    public static T DeserializeXml(string xmlObj)
    {
        XmlSerializer serializer = new XmlSerializer(typeof(T));
        using (StringReader reader = new StringReader(xmlObj))
        {
            return (T)serializer.Deserialize(reader);
        }
    }

    ///   
    /// 序列化类实例为XML  
    ///   
    ///   
    ///   
    ///   
    public static string SerializeXml(T obj)
    {
        using (StringWriter writer = new StringWriter())
        {
            new XmlSerializer(obj.GetType()).Serialize((TextWriter)writer, obj);
            return writer.ToString();
        }
    }
}
View Code

 

程序运行进行读取

List appAttrList = null;
XmlSerializer xmlSerializer = new XmlSerializer(typeof(List));
//_configPath为你的xml配置文件位置
using (StreamReader streamReader = new StreamReader(_configPath))
{
    appAttrList = xmlSerializer.Deserialize(streamReader) as List;
}

 

参考:

C#.NET解析XML(简单实例) 

 

C#解析XML文件

标签:get   反序   path   pen   ref   sch   summary   反序列化   部分   

原文地址:http://www.cnblogs.com/chenyangsocool/p/7575513.html


评论


亲,登录后才可以留言!