using System;
using System.Collections.Generic;
using System.Xml.Linq;
public class XmlHelper
{
private string m_filename = "";
private XDocument m_doc = null;
public XmlHelper(string filename)
{
m_filename = filename;
if (System.IO.File.Exists(filename))
m_doc = XDocument.Load(m_filename);
else
m_doc = new XDocument(new XDeclaration("1.0", "gbk", "yes"), new XElement("config"));
}
public string[] ReadStrings(string nodename)
{
List<string> resultlist = new List<string>();
XElement element = m_doc.Root.Element(nodename);
if (element != null)
{
foreach (XElement n in element.Nodes())
{
resultlist.Add(n.Value);
}
}
return resultlist.ToArray();
}
public void WriteStrings(string nodename, string[] items)
{
XElement element = m_doc.Root.Element(nodename);
if (element == null)
{
element = new XElement(nodename);
foreach (string item in items)
{
element.Add(new XElement("item") { Value = item });
}
m_doc.Root.Add(element);
}
else
{
element.RemoveAll();
foreach (string item in items)
{
element.Add(new XElement("item") { Value = item });
}
}
}
public int ReadInteger(string nodename)
{
int retvalue = -1;
XElement element = m_doc.Root.Element(nodename);
if (element != null)
{
retvalue = Convert.ToInt32(element.Value);
}
return retvalue;
}
public void WriteInteger(string nodename, int intvalue)
{
XElement element = m_doc.Root.Element(nodename);
if (element == null)
{
element = new XElement(nodename, intvalue);
m_doc.Root.Add(element);
}
else
{
element.RemoveAll();
element.SetValue(intvalue);
}
}
public void Save()
{
m_doc.Save(m_filename);
}
}
C# XmlHelper
最新推荐文章于 2024-06-21 18:49:43 发布