说明:
在xml中不需要做任何特别操作,即ID列为string或int时,向xml文件中添加数据时实现ID的自增长
XMl文件:
XML文件
<?xml version="1.0" standalone="yes"?>
<Users xmlns="http://tempuri.org/User.xsd">
<user xmlns="">
<userid>1</userid>
<username>李燕平</username>
<userpass>123</userpass>
<usermail>leellyp@gmail.com</usermail>
<usersite>438803482</usersite>
<usermsn>tenghoo@hotmail.com</usermsn>
<ndate>2006-9-8 16:22:19 </ndate>
<userpic>20060908041706167.jpg</userpic>
</user>
</Users>
<?xml version="1.0" standalone="yes"?>
<Users xmlns="http://tempuri.org/User.xsd">
<user xmlns="">
<userid>1</userid>
<username>李燕平</username>
<userpass>123</userpass>
<usermail>leellyp@gmail.com</usermail>
<usersite>438803482</usersite>
<usermsn>tenghoo@hotmail.com</usermsn>
<ndate>2006-9-8 16:22:19 </ndate>
<userpic>20060908041706167.jpg</userpic>
</user>
</Users>
以下给出三种方法:
一,代码如下
法一
XmlDocument doc = new XmlDocument();
string filename = Server.MapPath(".//XML//User.xml");
doc.Load(filename);
XmlNode root = doc.DocumentElement;
XmlNode user = doc.CreateElement("user");
int userid = doc.SelectSingleNode("Users").ChildNodes.Count;
XmlDocument doc = new XmlDocument();
string filename = Server.MapPath(".//XML//User.xml");
doc.Load(filename);
XmlNode root = doc.DocumentElement;
XmlNode user = doc.CreateElement("user");
int userid = doc.SelectSingleNode("Users").ChildNodes.Count;
二.代码如下:
法二
DataSet ds = new DataSet();
ds.ReadXml(filename);
int userid = ds.Tables[0].Rows.Count+1;
DataSet ds = new DataSet();
ds.ReadXml(filename);
int userid = ds.Tables[0].Rows.Count+1;
三,代码如下
法三
XmlDocument doc = new XmlDocument();
string filename = Server.MapPath(".//XML//User.xml");
doc.Load(filename);
XmlNode root = doc.DocumentElement;
XmlNode user = doc.CreateElement("user");
string userid =Convert.ToString(Convert.ToInt32(root.LastChild.ChildNodes[0].InnerText)+1);
XmlDocument doc = new XmlDocument();
string filename = Server.MapPath(".//XML//User.xml");
doc.Load(filename);
XmlNode root = doc.DocumentElement;
XmlNode user = doc.CreateElement("user");
string userid =Convert.ToString(Convert.ToInt32(root.LastChild.ChildNodes[0].InnerText)+1);