更新时间:2022-04-21 00:48:17
非常简单。检查以下代码,
Its very simple. Check the following code,
DataSet objDataSet = new DataSet();
objDataSet.ReadXml(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\users.xml");
DataRow objNewRow = objDataSet.Tables[0].NewRow();
objNewRow["PIN"] = "012345";
objNewRow["ID"] = "98765";
objNewRow["Name"] = "Testing User";
objNewRow["CheckingACCNum"] = "258741369";
objNewRow["CheckingACCBalance"] = "50000";
objNewRow["SavingACCNum"] = "789456123";
objNewRow["SavingACCBalance"] = "45000";
objNewRow["Address"] = "United States";
objNewRow["Phone"] = "1231231230";
objNewRow["tcounter"] = "10";
objNewRow["current"] = "565";
objDataSet.Tables[0].Rows.Add(objNewRow);
objDataSet.Tables[0].AcceptChanges();
objDataSet.Tables[0].WriteXml(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\new_users.xml");
我使用了桌面文件夹中的 user.xml 文件。您只需在以下函数中提供自己的xml文件路径。
I have used your user.xml file from my desktop folder. You just provide your own xml file path in the following functions.
objDataSet.ReadXml("Your XML file path");
objDataSet.Tables[0].WriteXml("Your XML file path");
我认为XMLDocument类将比XMLWriter更有帮助,只需创建新节点并将其附加到现有的xml
见下面的示例代码片段
I think XMLDocument class will help you more than XMLWriter, it is very easy just create new node and append it to existing xml
see below sample snippet
XmlDocument doc = new XmlDocument();
doc.Load("file.xml");
XmlElement foo = doc.CreateElement("foo");
XmlElement bar = doc.CreateElement("bar");
bar.InnerText = "whatever";
foo.AppendChild(bar);
doc.DocumentElement.AppendChild(foo);
doc.Save("file.xml");
我想为这个xml文件创建User节点:
I want to create "User" node to this xml file:
您显示的文件对您想要做的事情是错误的。
为了将用户添加到文件中,我认为您需要一个根节点。
您的文件
The file you show is wrong afainst what you want to do.
In order to add a user to the file, I think you need a root node.
Your file
<user pin="5111">
...
</user>
必须看起来像
must look like
<rootnode>
<user pin="5111">
...
</user>
</rootnode>
以便添加用户
节点
in order to add User
nodes
<rootnode>
<user pin="5111">
...
</user>
<user pin="5112">
...
</user>
</rootnode>
要更改XML文件,需要在内存中加载文件(使用XMLReader对象/类)。根据需要添加节点。完成后保存文件。如解决方案1中所示。
XML教程 [ ^ ]