Json与XML辅助类(读写存操作)

来源:互联网 发布:windows清理助手 编辑:程序博客网 时间:2024/05/23 19:25

Json与XML辅助类(读写存操作)

数据类

保存解析文件的路径 和文件的内容

    public class ConfigNode    {        protected string filePath;     //文件的路径        protected string contextRead;  //解析出来的文件内容    }//这里文件的路径  写绝对路径 例如:C:\Users\Administrator\Desktop\TestJson.json//如果写相对路径,代表该文件存放在bin/Debug文件夹下## Json通用类 ##

public class JsonHelper :ConfigNode
{
public T dataRead; //T类型的数据对象

    public JsonHelper() {    }    public JsonHelper(string filePath)    {        this.filePath = filePath;    }    public void Dispose()    {        throw new NotImplementedException();    }    public void GetConfigData()    {        throw new NotImplementedException();    }    public void Init()    {        Read();    }

//加载文件
public bool LoadFile(string lfilePath)
{
if (!File.Exists(lfilePath)) throw new Exception(“file load fail”);
try
{
using (StreamReader reader = File.OpenText(lfilePath) )
{
this.contextRead= reader.ReadToEnd();
}
}
catch (Exception e) {
throw new Exception(“file read fail”);
}
return true;
}

//将加载出来的文件内容转为T类型对象
public virtual void Read()
{
if(LoadFile(this.filePath))
dataRead= JsonMapper.ToObject(this.contextRead);
}

//将T类型数据对象保存在新路径
public void Save(string sfilePath = “newfile.json”)
{
string json = JsonMapper.ToJson(this.dataRead);
try
{
using (var sw = new StreamWriter(sfilePath,true))
{
sw.Write(json);
}
}
catch (Exception e)
{
throw new Exception(“file save fail”); ;
}
}

//将T类型数据对象 写入默认的文件中
public void Write(object newData)
{
if (!File.Exists(this.filePath)) throw new Exception(“file load fail”);
try {
using (var sw = new StreamWriter(this.filePath, true)) {
string json = JsonMapper.ToJson(newData);
sw.Write(json);
}
}
catch (Exception e) {
throw new Exception(“file write fail”);
}
}
}

XML同用类

之前写的

public T dataRead;

    public XmlHelper()    {    }    public XmlHelper(string filePath)    {        this.filePath = filePath;    }    public void Dispose()    {        throw new NotImplementedException();    }    public void GetConfigData()    {    }    public void Init()    {        Read();    }

//加载文件
public bool LoadFile(string lfilePath)
{
if (!File.Exists(lfilePath)) throw new Exception(“file load fail”);
try {
using (StreamReader reader = File.OpenText(lfilePath)) {
this.contextRead = reader.ReadToEnd();
}
}
catch (Exception e) {
throw new Exception(“file read fail”);
}
return true;
}

//将XML文件转为对象(反序列化)
public void Read()
{
if (LoadFile(this.filePath))
{
using (StreamReader reader = new StreamReader(this.filePath))
{
XmlSerializer xs = new XmlSerializer(typeof (T));
dataRead=(T)xs.Deserialize(reader);
}
}
}

//保存xml文件到新路径
public void Save(string sfilePath = “newfile.xml”)
{
if (LoadFile(sfilePath))
{
var sw = new StreamWriter(sfilePath, true);
sw.Write(this.contextRead);
}
}

//将新的数据对象 写入xml文件中
public void Write(object newData)
{
if (LoadFile(this.filePath))
{
try {
using (var stream = new StreamWriter(this.filePath, true)) {

                    StringWriter sw = new StringWriter();                    XmlSerializer s = new XmlSerializer(newData.GetType());                    s.Serialize(sw, newData);                    string myStr = sw.ToString();                    if (this.contextRead != "") {                        int i = sw.ToString().IndexOf("<" + newData.GetType().Name);                        int j = sw.ToString().IndexOf(">", i) + 3;                        myStr = myStr.Remove(0, j);                        int k = this.contextRead.IndexOf("</" + newData.GetType().Name);                        this.contextRead = this.contextRead.Remove(k);                        this.contextRead += myStr;                        stream.Close();                        using (var newstream = new StreamWriter(this.filePath, false))                        {                            newstream.Write(this.contextRead);                        }                    }                    else {                        this.contextRead = myStr;                        stream.Write(this.contextRead);                         }                }            }            catch (Exception e) {                throw new Exception("file write fail");            }        }
## XML通用类修改 ##

using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Data.Odbc;
using System.IO;
using System.Text;
using System.Xml;
using System.Linq;
using System.Xml.Serialization;
using System.Reflection;

namespace Ai.Runtime
{
public class XmlHelper : ConfigNode, IHelper
{
public T dataRead;

    public XmlHelper()    {    }    public XmlHelper(string filePath)    {        this.filePath = filePath;    }    public void Dispose()    {        throw new NotImplementedException();    }    public void GetConfigData()    {    }    public void Init()    {        Read();    }    public bool LoadFile(string lfilePath)    {        if (!File.Exists(lfilePath)) throw new Exception("file load fail");        try {            XmlDocument document = new XmlDocument();            document.Load(lfilePath);            this.contextRead = FormatText(document.DocumentElement as XmlNode, "", "");        }        catch (Exception e) {            throw new Exception("file read fail");        }        return true;    }    public void Read()    {        if (LoadFile(this.filePath))        {            using (StreamReader reader = new StreamReader(this.filePath))            {                XmlSerializer xs = new XmlSerializer(typeof (T));                dataRead=(T)xs.Deserialize(reader);            }        }    }    public void Save(string sfilePath = "newfile.xml")    {        if (LoadFile(sfilePath))        {            var sw = new StreamWriter(sfilePath, true);            sw.Write(this.contextRead);        }    }    public void Write(object newData)    {        XmlDocument document = new XmlDocument();        document.Load(this.filePath);        XmlElement root = document.DocumentElement;        XmlElement newobject = document.CreateElement(newData.GetType().Name);        List<XmlElement> xmleleList = new List<XmlElement>();        List<XmlText> xmltextList = new List<XmlText>();        foreach (PropertyInfo pi in newData.GetType().GetProperties())        {            var name = pi.Name;//获得属性的名字            var value = pi.GetValue(newData, null);//用pi.GetValue获得值            xmleleList.Add(document.CreateElement(name));            xmltextList.Add(document.CreateTextNode((string)value));        }        for (int i=0;i<xmleleList.Count;i++)        {            newobject.AppendChild(xmleleList[i]);            xmleleList[i].AppendChild(xmltextList[i]);        }        root.InsertAfter(newobject, root.LastChild);        document.Save(this.filePath);    }    public string FormatText(XmlNode node,string text,string indent)    {        if(node is XmlText)        {            text += node.Value;            return text;        }        if(string.IsNullOrEmpty(indent))        {            indent = "";        }        else        {            text += "\r\n" + indent;        }        if(node is XmlComment)        {            text += node.OuterXml;            return text;        }        text += "<" + node.Name;        if(node.Attributes.Count>0)        {            AddAttribute(node, ref text);        }        if (node.HasChildNodes)        {            text += ">";            foreach (XmlNode child in node.ChildNodes)            {                text = FormatText(child, text, indent + " ");            }            if (node.ChildNodes.Count == 1 && (node.FirstChild is XmlText || node.FirstChild is XmlComment))            {                text += "</" + node.Name + ">";            }            else            {                text += "\r\n" + indent + "</" + node.Name + ">";            }        }        else            text += "/>";        return text;    }    private void AddAttribute(XmlNode node,ref string text)    {        foreach(XmlAttribute xa in node.Attributes)        {            text += " " + xa.Name + "='" + xa.Value + "'";        }    }}

}
“`

原创粉丝点击