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;
}
}