c#读取/保存 Xml文件

  •  XmlDocument读取

Xml文件:



   嘿嘿嘿
  李白
  100

读取方法:

 

            //using System.Xml;           
            XmlDocument doc = new XmlDocument();
            doc.Load(@"F:\a.xml");//XML文件路径
            XmlNodeList LiNode = doc.SelectNodes(@"/book/title");//要读取xml子目录路径
            foreach (XmlNode item in LiNode)
            {
                textBox3.Text = item.InnerXml;//获取指定xml子目录的值
                textBox1.Text = item.Attributes["id"].Value;//获取指定xml子目录属性是id的值
                textBox2.Text = item.Attributes["name"].Value;//获取指定xml子目录属性是name的值
            }
  • Linq读取 

 Xml文件:



  
    
      
    
    
      7200
    
    
      wxfabe9ea3ac8ec2c5
    
    
      1ce4a1b2c4254c798b977195c85b6504
    
  
//Linq 查询
string _Path = System.Configuration.ConfigurationManager.AppSettings["WeChatXMLFilePath"].ToString();
_XElement = XElement.Load(_Path);
IEnumerable elements = from ele in _XElement.Elements("WeChat")
                                             select ele;
List modelList = new List();
foreach (var ele in elements)
{
    WeChatModel model = new WeChatModel();
    model.access_token = ele.Element("AccessToken").Value;
    model.expires_in = Convert.ToInt32(ele.Element("ExpiresIn").Value);
    model.Appid = ele.Element("Appid").Value;
    model.Secret = ele.Element("Secret").Value;

    modelList.Add(model);
}
return modelList;
  •  XmlDocument保存

保存方法:

            //循环里改为赋值然后保存即可,其他不变
            foreach (XmlNode item in LiNode)
            {
               item.InnerXml = @" test";
                item.InnerText = @" test2";
            }
            doc.Save(@"F:\项目练习\a.xml");//保存到指定目录

注意:

在测试保存使用InnerXml与InnerText的时候:

    InnerXml保存后:XML文件未乱码,任意属性读取未乱码

    InnerText保存后:XML文件乱码,只能使用InnerText读取,否则读取还是乱码

PS:其实也不算是乱码,只是转成了标示而已(如果不是很明白试一下就明白了,并不复杂)

如: <bbb>test2</bbb>

  • Linq保存(XML中不能写备注)

IEnumerable element = from ele in _XElement.Elements("WeChat")
                                            select ele;
            XElement first = element.First();
            ///设置新的属性
            if (!string.IsNullOrWhiteSpace(model.access_token))
            {                
                ((System.Xml.Linq.XElement)first.Element("AccessToken").FirstNode).Value= model.access_token;
            }
            if (!string.IsNullOrWhiteSpace(model.expires_in.ToString()))
            {
                ((System.Xml.Linq.XElement)first.Element("ExpiresIn").FirstNode).Value = model.expires_in.ToString();
            }
            if (!string.IsNullOrWhiteSpace(model.Appid))
            {
                ((System.Xml.Linq.XElement)first.Element("Appid").FirstNode).Value = model.Appid;
            }
            if (!string.IsNullOrWhiteSpace(model.Secret))
            {
                ((System.Xml.Linq.XElement)first.Element("Secret").FirstNode).Value = model.Secret;
            }
            _XElement.Save(_Path);

 

你可能感兴趣的:(asp-net)