您的位置:首页 > 编程语言 > C#

c#读写xml文件

2016-04-19 13:27 549 查看
结果:这种格式:只有一个node结点

<?xml version="1.0" encoding="utf-8"?>
<RootName>
<OnePersonNode name="LiLei" sex="male" age="12" />
<OnePersonNode name="HanMeiMei" sex="female" age="11" />
</RootName>


using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Mime;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace xmlTest
{
class Program
{
static void Main(string[] args)
{
;
string xmlSavePath = "data.xml";
//-------------BEGIN-写 xml -------------------

Program testProgram = new Program();

//--初始化xml数据类
List<PersonInfo> personInfoList;
//填充具体数据
testProgram.CreateData(out personInfoList);
//真正创建
testProgram.CreateXmlFile(personInfoList, xmlSavePath);

//------------END--------------

//---BEGIN--读 xml---------

List<PersonInfo> mPeronInfoList = new List<PersonInfo>();
XmlDocument readXml = new XmlDocument();
readXml.Load(xmlSavePath);
//获取根节点
XmlNode xmlRootNode = readXml.SelectSingleNode(PersonInfo.mRootName);
if (xmlRootNode != null)
{
//所有节点
XmlNodeList nodeList = xmlRootNode.ChildNodes;

//--------BEGIN-修改--------
//修改节点的值 如没有则新加
for (int i = 0; i < nodeList.Count; ++i)
{
XmlNode tempNode = nodeList[i];
if (tempNode != null)
{
XmlElement oneElement = (XmlElement)tempNode;
if (oneElement.GetAttribute(PersonInfo.Name) == "LiLei")
{
oneElement.SetAttribute(PersonInfo.Age, "47");
}
}
}
//----------END-----------

//填充数据
for (int i = 0; i < nodeList.Count; ++i)
{
XmlNode tempNode = nodeList[i];
if (tempNode != null)
{
XmlElement oneElement = (XmlElement)tempNode;
PersonInfo tempPersonInfo = new PersonInfo(oneElement.GetAttribute(PersonInfo.Name)
, oneElement.GetAttribute(PersonInfo.Sex)
, oneElement.GetAttribute(PersonInfo.Age));
mPeronInfoList.Add(tempPersonInfo);
}
}

}
//----------END------------

//打印测试:
for (int i = 0; i < mPeronInfoList.Count; ++i)
{
PersonInfo info = mPeronInfoList[i];
Console.Write(PersonInfo.Name + ":" + info.mNameVal + PersonInfo.Sex + ":" + info.mSexVal + PersonInfo.Age + ":" + info.mAgeVal);
Console.WriteLine();
}
}

/// <summary>
/// 一个节点的信息
/// </summary>

private class PersonInfo
{
public const string mRootName = "RootName";//根节点名称
public const string mNodeName = "OnePersonNode";//node节点名称

public const int AttSize = 3;

public const string Name = "Name";
public const string Sex = "Sex";
public const string Age = "Age";

public string mNameVal = string.Empty;
public string mSexVal = string.Empty;
public string mAgeVal = string.Empty;

public PersonInfo(string fName, string fSex, string fAge)
{
mNameVal = fName;
mSexVal = fSex;
mAgeVal = fAge;
}

public PersonInfo(string[] arr)
{
if (arr != null && arr.Length == AttSize)
{
mNameVal = arr[0];
mSexVal = arr[1];
mAgeVal = arr[2];
}
}

}

/// <summary>
/// 数据的创建
/// </summary>
private void CreateData(out List<PersonInfo> personInfoList)
{
personInfoList = new List<PersonInfo>();
string[] valArr = { "LiLei", "male", "12" };
PersonInfo tempInfo = new PersonInfo(valArr);
personInfoList.Add(tempInfo);

string[] valArr_2 = { "HanMeiMei", "female", "11" };
tempInfo = new PersonInfo(valArr_2);
personInfoList.Add(tempInfo);
}

private void CreateXmlFile(List<PersonInfo> personList, string savePath)
{
//-- 创建xml
XmlDocument xmlDoc = new XmlDocument();
XmlNode node = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", "");
xmlDoc.AppendChild(node);
//-- 创建root
XmlNode root = xmlDoc.CreateElement(PersonInfo.mRootName);
xmlDoc.AppendChild(root);

//--填充每个node数据
for (int i = 0; i < personList.Count; ++i)
{
XmlNode tempNde = xmlDoc.CreateNode(XmlNodeType.Element, PersonInfo.mNodeName, null);
PersonInfo tempNodeInfo = personList[i];

CreateNodeAttribute(xmlDoc, tempNde, PersonInfo.Name, tempNodeInfo.mNameVal);
CreateNodeAttribute(xmlDoc, tempNde, PersonInfo.Sex, tempNodeInfo.mSexVal);
CreateNodeAttribute(xmlDoc, tempNde, PersonInfo.Age, tempNodeInfo.mAgeVal);
//添加节点
root.AppendChild(tempNde);
}

//保存数据
try
{
xmlDoc.Save(savePath);
}
catch (Exception e)
{
//显示错误信息
Console.WriteLine(e.Message);
}
}

/// <summary>
///创建xml node内的元素
/// </summary>
public void CreateNodeAttribute(XmlDocument xmlDoc, XmlNode node, string attributeName, string attVal)
{
if (xmlDoc != null && node != null)
{
XmlAttribute attribute = xmlDoc.CreateAttribute(attributeName);
attribute.Value = attVal;
if (node.Attributes != null)
{ node.Attributes.Append(attribute); }
}
else
{
Debug.Assert(false, "xmlDoc or node is null!");
}
}
}

}


获取文件的时间记录:

/// <summary>
/// 获取这个路径下的数据
/// </summary>
/// <param name="timeInfoList">填充到这里</param>
/// <param name="fileName">路径</param>
private void GetFileTimeData(ref List<TimeNodeInfo> timeInfoList, string fileName)
{
if (Directory.Exists(fileName))
{
DirectoryInfo direction = new DirectoryInfo(fileName);
FileInfo[] files = direction.GetFiles("*", SearchOption.AllDirectories); ;
string titleName = "正在检查" + fileName;
for (int i = 0; i < files.Length; i++)
{
if (!files[i].Name.EndsWith(".svn-base"))
{
int stringIdx = files[i].DirectoryName.IndexOf("Assets\\", StringComparison.Ordinal);
string assetName = files[i].DirectoryName.Substring(stringIdx) + "\\" + files[i].Name;
TimeNodeInfo tempTimeInfo = new TimeNodeInfo(assetName, files[i].LastWriteTime.Ticks.ToString());
timeInfoList.Add(tempTimeInfo);
EditorUtility.DisplayProgressBar(titleName, assetName, (float)i / (float)files.Length);
}
}
}
}


下面是: 查询指定路径下, 文件的时间信息,并且 提供 某个文件是否被修改,然后进行时间数据的刷新操作。。

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using UnityEditor;
using UnityEngine;
using Debug = System.Diagnostics.Debug;

/// <summary>
/// 文件的时间信息存储
/// </summary>
namespace Assets.Editor.ResTimeInfo
{
/// <summary>
/// 单个节点的数据信息
/// </summary>
public class TimeNodeInfo
{
public const int mAttributeSize = 3;//一个node几个属性
public const string FilePathName = "FilePathName";
public const string TimeName = "Time";
public const string YMRTimeName = "showTime";//直观形式

public string mFilePath = string.Empty;
public string mTime = string.Empty;
public string mYMRtime = string.Empty;//年月日time形式

public TimeNodeInfo(string fFilePath, string fTime, string ymrTime)
{
mFilePath = fFilePath;
mTime = fTime;
mYMRtime = ymrTime;
}

public TimeNodeInfo(string[] arr)
{
if (arr != null && arr.Length == mAttributeSize)
{
mFilePath = arr[0];
mTime = arr[1];
mYMRtime = arr[2];
}
}
}

class XmlTimeInfo
{
public XmlTimeInfo()
{

}

private static XmlTimeInfo mInstance = null;
public static XmlTimeInfo Instance
{
get
{
if (mInstance != null)
{
return mInstance;
}
else
{
mInstance = new XmlTimeInfo();
return mInstance;
}
}
}

public static string RootPath = Application.dataPath;

public string AllFileSavePath = (RootPath.Replace("Assets", "RVL") + "/AllFileSavePath.xml");//所有文件时间数据存储路径
public string ChangeFileSavePath = RootPath.Replace("Assets", "RVL") + "/ChangeFileSavePath.xml";//修改的文件存储路径 。。。估计不需要

public string ResPath = "Assets/Res";//读取文件的路径Res
public string ResourcePath = "Assets/Resources";//读取文件的路径Resources

public string RootName = "RootName";
public string NodeName = "Property";

private XmlNode mRoot;

private Dictionary<string, TimeNodeInfo> mTimeInfoDic = new Dictionary<string, TimeNodeInfo>();

XmlDocument xmlDoc = new XmlDocument();
/// <summary>
/// 保存所有文件的时间信息
/// AllFileTimeInfo.xml
/// </summary>
public void SaveAllResTimeInfo()
{
//--

//填充具体数据
CreateInitData(ref mTimeInfoDic);
CreateXmlFile(mTimeInfoDic, AllFileSavePath);

}
/// <summary>
/// 保存所有修改文件的时间信息
/// ChangeFileTimeInfo.xml
/// </summary>
public void SaveChangeResTimeInfo()
{

}

/// <summary>
/// 这个文件是否更改?
/// </summary> "Assets\\Editor\\AssetBuild\\Old\\999.txt"
/// <param name="fFilePath">类似路径:"Assets\Editor\AssetBuild\Old\NewCreateBundleEditor.cs.meta"</param>
/// <returns></returns>
public bool IsFileChange(string fFilePath)
{
//load当前xml
xmlDoc.Load(AllFileSavePath);
//1.获取当前文件修改时间
FileInfo nowFileInfo = null;
try
{
nowFileInfo = new FileInfo(fFilePath);
}
catch (Exception e)
{
LogSystem.LogError("Error: fFilePath is not find :", fFilePath, "  ", e.ToString());
}

if (nowFileInfo != null)
{
//2.获取dic中此文件的时间
string nowFileTime = nowFileInfo.LastWriteTime.Ticks.ToString();
string ymrTime = nowFileInfo.LastWriteTime.ToString();
TimeNodeInfo outInfo;

if (mTimeInfoDic.TryGetValue(fFilePath, out outInfo))
{
//3.时间是否相同
if (outInfo.mTime == nowFileTime)
{
return true;
}
else
{
mTimeInfoDic[fFilePath].mTime = nowFileTime;
mTimeInfoDic[fFilePath].mYMRtime = ymrTime;
//4.修改xml内容
ChangeXmlElement(mTimeInfoDic[fFilePath], AllFileSavePath);
return false;
}
}
else //4.说明是新的文件 add
{
outInfo = new TimeNodeInfo(fFilePath, nowFileTime, ymrTime);
mTimeInfoDic.Add(fFilePath, outInfo);
//新加内容
AddXmlOneElement(outInfo, AllFileSavePath);
return true;
}
}
else
{
LogSystem.LogError("this path file info is null!" + fFilePath);
}
return false;
}

#region xml数据相关
private void CreateInitData(ref Dictionary<string, TimeNodeInfo> fTimeInfoDic)
{
//-- 创建xml
//-- 创建root
mRoot = xmlDoc.SelectSingleNode(RootName);
if (mRoot == null)
{
XmlNode node = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", "");
xmlDoc.AppendChild(node);

mRoot = xmlDoc.CreateElement(RootName);
xmlDoc.AppendChild(mRoot);
}

string fullPath = "Assets/Editor/AssetBuild/Old" + "/";
GetFileTimeData(ref fTimeInfoDic, fullPath);
fullPath = "Assets/Editor/AssetBuild/New" + "/";
GetFileTimeData(ref fTimeInfoDic, fullPath);
EditorUtility.ClearProgressBar();
}

/// <summary>
/// 获取这个路径下的时间数据
/// </summary>
/// <param name="timeInfoList">填充到这里</param>
/// <param name="filePath">路径</param>
private void GetFileTimeData(ref Dictionary<string, TimeNodeInfo> fTimeInfoDic, string filePath)
{
if (Directory.Exists(filePath))
{
DirectoryInfo direction = new DirectoryInfo(filePath);
FileInfo[] files = direction.GetFiles("*", SearchOption.AllDirectories); ;
string titleName = "正在检查" + filePath;
for (int i = 0; i < files.Length; i++)
{
if (!files[i].Name.EndsWith(".svn-base"))
{
string assetName = GetAssetsPath(files[i].DirectoryName, files[i].Name);
TimeNodeInfo tempTimeInfo = new TimeNodeInfo(assetName,
files[i].LastWriteTime.Ticks.ToString(),
files[i].LastWriteTime.ToString());

if (!fTimeInfoDic.ContainsKey(tempTimeInfo.mFilePath))
{
fTimeInfoDic.Add(tempTimeInfo.mFilePath, tempTimeInfo);
}
else
{
fTimeInfoDic[tempTimeInfo.mFilePath] = tempTimeInfo;
}

EditorUtility.DisplayProgressBar(titleName, assetName, (float)i / (float)files.Length);
}
}
}
}

/// <summary>
/// 获取 文件相对 Assets文件下的路径
/// </summary>
/// <returns></returns>
private string GetAssetsPath(string fDirectoryPath, string fileName)
{
int stringIdx = fDirectoryPath.IndexOf("Assets\\", StringComparison.Ordinal);
string assetName = fDirectoryPath.Substring(stringIdx) + "\\" + fileName;

return assetName;
}

/// <summary>
/// 初始创建xml一次
/// </summary>
/// <param name="timeList"></param>
/// <param name="savePath"></param>
private void CreateXmlFile(Dictionary<string, TimeNodeInfo> fTimeInfoDic, string savePath)
{
//清除老数据
RemoveOldData();
//--填充每个node数据
foreach (KeyValuePair<string, TimeNodeInfo> kvp in fTimeInfoDic)
{
XmlNode tempNde = xmlDoc.CreateNode(XmlNodeType.Element, NodeName, null);
TimeNodeInfo tempNodeInfo = kvp.Value;

CreateNodeAttribute(xmlDoc, tempNde, TimeNodeInfo.FilePathName, tempNodeInfo.mFilePath);
CreateNodeAttribute(xmlDoc, tempNde, TimeNodeInfo.TimeName, tempNodeInfo.mTime);
CreateNodeAttribute(xmlDoc, tempNde, TimeNodeInfo.YMRTimeName, tempNodeInfo.mYMRtime);
//添加节点
mRoot.AppendChild(tempNde);

}
//保存数据
try
{
xmlDoc.Save(savePath);
}
catch (Exception e)
{
//显示错误信息
Console.WriteLine(e.Message);
}
}
/// <summary>
///创建xml node内的元素
/// </summary>
public void CreateNodeAttribute(XmlDocument xmlDoc, XmlNode node, string attributeName, string attVal)
{
if (xmlDoc != null && node != null)
{
XmlAttribute attribute = xmlDoc.CreateAttribute(attributeName);
attribute.Value = attVal;
if (node.Attributes != null)
{ node.Attributes.Append(attribute); }
}
else
{
Debug.Assert(false, "xmlDoc or node is null!");
}
}

/// <summary>
/// 修改一个元素的时间
/// </summary>
public void ChangeXmlElement(TimeNodeInfo fNode, string savePath)
{
XmlNode xmlRootNode = xmlDoc.SelectSingleNode(RootName);
if (xmlRootNode != null)
{
//所有节点
XmlNodeList nodeList = xmlRootNode.ChildNodes;
for (int i = 0; i < nodeList.Count; ++i)
{
XmlNode tempNode = nodeList[i];
if (tempNode != null)
{
XmlElement oneElement = (XmlElement)tempNode;
if (oneElement.GetAttribute(TimeNodeInfo.FilePathName) == fNode.mFilePath)
{
oneElement.SetAttribute(TimeNodeInfo.TimeName, fNode.mTime);
oneElement.SetAttribute(TimeNodeInfo.YMRTimeName, fNode.mYMRtime);
xmlDoc.Save(savePath);
}
}
}
}
}
/// <summary>
///  添加一个元素
/// </summary>
public void AddXmlOneElement(TimeNodeInfo fNode, string savePath)
{
XmlNode xmlRootNode = xmlDoc.SelectSingleNode(RootName);
if (xmlRootNode != null)
{
XmlNode tempNde = xmlDoc.CreateNode(XmlNodeType.Element, NodeName, null);
CreateNodeAttribute(xmlDoc, tempNde, TimeNodeInfo.FilePathName, fNode.mFilePath);
CreateNodeAttribute(xmlDoc, tempNde, TimeNodeInfo.TimeName, fNode.mTime);
CreateNodeAttribute(xmlDoc, tempNde, TimeNodeInfo.YMRTimeName, fNode.mYMRtime);
xmlRootNode.AppendChild(tempNde);
try
{
xmlDoc.Save(savePath);
}
catch (Exception e)
{
//显示错误信息
Console.WriteLine(e.Message);
}
}
}

public void RemoveOldData()
{

XmlNode xmlRootNode = xmlDoc.SelectSingleNode(RootName);
if (xmlRootNode != null)
{
xmlRootNode.RemoveAll();
}
}

#endregion
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: