一个比较有用的XML文件操作类 C#代码 可以继续扩展

public class CXml

{

private string strXmlFile;

private XmlDocument objXmlDoc = new XmlDocument();

public CXml(string xmlFile)

{

//构造函数

try

{

objXmlDoc.Load(xmlFile);

}

catch

{

}

strXmlFile = xmlFile;

}

public DataView GetData(string xmlPathNode)

{

//查找数据返回一个DataView

DataSet ds = new DataSet();

StringReader read = new StringReader(objXmlDoc.SelectSingleNode(xmlPathNode).OuterXml);

ds.ReadXml(read);

return ds.Tables[0].DefaultView;

}

public void Replace(string xmlPathNode,string content)

{

//更新节点內容

objXmlDoc.SelectSingleNode(xmlPathNode).InnerText = content;

}

public void Delete(string node)

{

//刪除一个节点

string mainNode = node.Substring(0,node.LastIndexOf("/"));

objXmlDoc.SelectSingleNode(mainNode).RemoveChild(objXmlDoc.SelectSingleNode(node));

}

public void InsertNode(string mainNode,string childNode,string element,string content)

{

//插入一节点和此节点的一子节点

XmlNode objRootNode = objXmlDoc.SelectSingleNode(mainNode);

XmlElement objChildNode = objXmlDoc.CreateElement(childNode);

objRootNode.AppendChild(objChildNode);

XmlElement objElement = objXmlDoc.CreateElement(element);

objElement.InnerText = content;

objChildNode.AppendChild(objElement);

}

public void InsertElement(string mainNode,string element,string attrib,string attribContent,string content)

{

//插入一个节点带一个属性

XmlNode objNode = objXmlDoc.SelectSingleNode(mainNode);

XmlElement objElement = objXmlDoc.CreateElement(element);

objElement.SetAttribute(attrib,attribContent);

objElement.InnerText = content;

objNode.AppendChild(objElement);

}

public void InsertElement(string mainNode,string element,string content)

{

//插入一个节点不带属性

XmlNode objNode = objXmlDoc.SelectSingleNode(mainNode);

XmlElement objElement = objXmlDoc.CreateElement(element);

objElement.InnerText = content;

objNode.AppendChild(objElement);

}

public void Save()

{

//保存XML文件

try

{

objXmlDoc.Save(strXmlFile);

}

catch

{

}

objXmlDoc = null;

}

}

你可能感兴趣的:(文件操作)