C#读写XML文件

来源:转载

使用Configuration读取xml文件

XML文件格式





读取:


System.Configuration.ConfigurationManager.AppSettings["WebPath"];
xml文件
<?xml version="1.0" encoding="utf-8"?>
















1
2
3
4
5









读写类
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
namespace Demo.Xml
{
class XMlDocumentHandler
{
private string configxml;
public string Configxml
{
get
{
return "..//..//config.xml";
}
set
{
configxml = value;
}
}
static void Main(string[] args)
{
try
{
XMlDocumentHandler xmlHandler = new XMlDocumentHandler();
System.Xml.Linq.XDocument xmlDoc = xmlHandler.IntiXmlMessage();
//xmlHandler.LoadPluginFeatures(xmlDoc);
xmlHandler.AddXmlNode(xmlDoc);
xmlDoc.Save(xmlHandler.Configxml);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
//Console.ReadLine();
}
public Dictionary xmlMsg = new Dictionary();
public string ContentSrc;
///
/// Load config.xml and Get Document Project
///

public System.Xml.Linq.XDocument IntiXmlMessage()
{
if (File.Exists(Configxml))
{
System.Xml.Linq.XDocument xmlDoc;
using (StreamReader strRead = new StreamReader(Configxml))
{
xmlDoc = System.Xml.Linq.XDocument.Parse(strRead.ReadToEnd());
}
return xmlDoc;
}
return null;
}
///
/// Get Nodes Vale
///

/// XDocumnet Project
private void LoadPluginFeatures(System.Xml.Linq.XDocument document)
{
var features = from feats in document.Descendants()
where feats.Name.LocalName == "feature"
select feats;
foreach (var feature in features)
{
string name = (string)feature.Attribute("name");
var value = (from results in feature.Descendants()
where results.Name.LocalName == "param" && ((string)results.Attribute("name") == "win")
select results).FirstOrDefault();
if (value!=null)
{
xmlMsg.Add((string)value.Attribute("name"), (string)value.Attribute("value"));
}
}
//获取Content节点的值
var contentsTag = (from results in document.Descendants()
where results.Name.LocalName == "content"
select results).FirstOrDefault();
if (contentsTag != null)
{
var src = contentsTag.Attribute("src");
ContentSrc = (string)src.Value;
}
}
///
/// Add XmlDocument Node
///

private void AddXmlNode(System.Xml.Linq.XDocument xDoc)
{
var value = (from results in xDoc.Descendants()
where results.Name.LocalName == "access"
select results).FirstOrDefault();
XElement xmlTree = new XElement("Root",
new XElement("Child1", 1),
new XElement("Child2", 2),
new XElement("Child3", 3),
new XElement("Child4", 4),
new XElement("Child5", 5)
);
value.Add(xmlTree);
}
}
}

分享给朋友:
您可能感兴趣的文章:
随机阅读: