c#语言xml的读取和实例化的常用方式

1、使用XmlDocument或XDocument读取/创建xml文件

下面代码是读取

XmlDocument doc = new XmlDocument();
xml.Load("D:\\Atlas\\123.xml");

//CustomerInfo是自己定义的实体
List lists = new List();
XmlNodeList list = doc.SelectNodes("/Table/row");
 
foreach (XmlNode item in list)
{
    CustomerInfo cust = new CustomerInfo();
    cust.Version = item.Attributes["Version"].Value;
    cust.AppId = item.Attributes["AppId"].Value;
    cust.CustomerID = item["CustomerID"].InnerText;
    cust.CompanyName = item["CompanyName"].InnerText;
    cust.ContactName = item["ContactName"].InnerText;
    lists.Add(cust);
}

下面代码是创建

//使用XmlDocument创建xml
XmlDocument xmldoc = new XmlDocument();
XmlDeclaration xmldec = xmldoc.CreateXmlDeclaration("1.0", "utf-8", "yes");
xmldoc.AppendChild(xmldec);
                    
//添加根节点
XmlElement rootElement = xmldoc.CreateElement("StandardItem");
rootElement.SetAttribute("Name", model.name);
xmldoc.AppendChild(rootElement);

//添加根节点下的子节点元素
XmlElement classElement = xmldoc.CreateElement("ItemGroup");
rootElement.AppendChild(classElement);

//这里递归添加节点
XmlElement childElement = xmldoc.CreateElement("StandardItem");
childElement.SetAttribute("Name", model.name);
XmlElement groupElement = xmldoc.CreateElement("ItemGroup");
childElement.AppendChild(groupElement);
classElement.AppendChild(childElement);

//保存文件
xmldoc.Save("D:\\Atlas\\abc.xml");

2、使用System.Xml.Serialization,将对象序列化到 XML 文档中和从 XML 文档中反序列化对象。

下面代码是读取

/// 
/// 将XML转换成实体对象
/// 
/// 实体类型
/// XML
public static T DESerializer(string strXML) where T : class
{
    try
    {
        using (StringReader sr = new StringReader(strXML))
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            return serializer.Deserialize(sr) as T;
        }
    }
    catch (Exception ex)
    {
        throw new Exception("将XML转换成实体对象异常", ex);
    }
}
ConfigModel config = XmlSerializeHelper.DESerializer(FileOperationHelper.ReadStringFromFile("D:\\Config.xml", FileMode.Open));

下面代码是写入

/// 
/// 将实体对象转换成XML
/// 
/// 实体类型
/// 实体对象
public static string XmlSerialize(T obj)
{
    try
    {
        using (StringWriter sw = new StringWriter())
        {
            Type t = obj.GetType();
            XmlSerializer serializer = new XmlSerializer(obj.GetType());
            serializer.Serialize(sw, obj);
            sw.Close();
            return sw.ToString();
        }
    }
    catch (Exception ex)
    {
        throw new Exception("将实体对象转换成XML异常", ex);
    }
}

 

/// 
        /// 将字符串写入到文件
        /// 
        /// 字符串
        /// 文件路径
        /// 文件操作模式
        /// 
        public static bool WriteStringToFile(string strXML, string filePath, FileMode mode)
        {
            try
            {
                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                }
                FileStream fs = new FileStream(filePath, mode);
                byte[] data = System.Text.Encoding.UTF8.GetBytes(strXML);
                //开始写入
                fs.Write(data, 0, data.Length);
                //清空缓冲区、关闭流
                fs.Flush();
                fs.Close();

                return true;
            }
            catch (Exception ex)
            {
                throw new Exception("文件写入失败", ex);
            }
        }
string stageModelXml = XmlSerializeHelper.XmlSerialize(newModel);
string filePath = "D:\\stage.xml";
FileOperationHelper.WriteStringToFile(stageModelXml, filePath, FileMode.Create);

 

你可能感兴趣的:(c#语言xml的读取和实例化的常用方式)