[ASP.net(C#)]XML操作类(一)
2024-07-10 13:00:16
供稿:网友
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();
菜鸟学堂: