public class XMLControl
{
protected string strXMLFile;
protected XMLDocument objXMLDoc = new XMLDocument();
public XMLControl(string XMLFile)
{
//
// TODO: 在這裡加入建構函式的程式碼
//
try
{
objXMLDoc.Load(XMLFile);
}
catch (System.Exception ex)
{
throw ex;
}
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()
{
//保存文檔。
try
{
objXMLDoc.Save(strXMLFile);
}
catch (System.Exception ex)
{
throw ex;
}
objXMLDoc = null;
}
}
=========================================================
实例应用:
string strXMLFile = Server.MapPath("TestXML.XML");
XMLControl XMLTool = new XMLControl(strXMLFile);
// 數據顯視
// dgList.DataSource = XMLTool.GetData("Book/Authors[ISBN=\"0002\"]");
// dgList.DataBind();
// 更新元素內容
// XMLTool.Replace("Book/Authors[ISBN=\"0002\"]/Content","ppppppp");
// XMLTool.Save();
// 添加一個新節點
// XMLTool.InsertNode("Book","Author","ISBN","0004");
// XMLTool.InsertElement("Book/Author[ISBN=\"0004\"]","Content","aaaaaaaaa");
// XMLTool.InsertElement("Book/Author[ISBN=\"0004\"]","Title","Sex","man","iiiiiiii");
// XMLTool.Save();
// 刪除一個指定節點的所有內容和屬性
// XMLTool.Delete("Book/Author[ISBN=\"0004\"]");
// XMLTool.Save();
// 刪除一個指定節點的子節點
// XMLTool.Delete("Book/Authors[ISBN=\"0003\"]");
// XMLTool.Save();