下面的代码是customerRecord
在 XML 文件中追加 a 的函数。我这里有两个问题:
1.追加记录时,如何检查xml中是否已经存在id
and的值??2.如何按或按
客户搜索并显示??Mobile
id
Mobile
textboxes
private const string FileName = @"C:\test\Person.xml";
private void button1_Click(object sender, EventArgs e)
{
var xmlDoc = new XmlDocument();
xmlDoc.Load(FileName);
var subRoot = xmlDoc.CreateElement("Customer");
subRoot.SetAttribute("id", textBox6.Text.Trim());
var firstName = xmlDoc.CreateElement("FirstName");
var xmlTextUserName = xmlDoc.CreateTextNode(textBox1.Text.Trim());
firstName.AppendChild(xmlTextUserName);
subRoot.AppendChild(firstName);
if (xmlDoc.DocumentElement != null)
xmlDoc.DocumentElement.AppendChild(subRoot);
var email = xmlDoc.CreateElement("LastName");
var xmlTextEmail = xmlDoc.CreateTextNode(textBox2.Text.Trim());
email.AppendChild(xmlTextEmail);
subRoot.AppendChild(email);
if (xmlDoc.DocumentElement != null)
xmlDoc.DocumentElement.AppendChild(subRoot);
var mobile = xmlDoc.CreateElement("Mobile");
var xmlTextMobile = xmlDoc.CreateTextNode(textBox3.Text.Trim());
mobile.AppendChild(xmlTextMobile);
subRoot.AppendChild(mobile);
if (xmlDoc.DocumentElement != null)
xmlDoc.DocumentElement.AppendChild(subRoot);
var address = xmlDoc.CreateElement("Address");
var xmlTextAddress = xmlDoc.CreateTextNode(textBox4.Text.Trim());
address.AppendChild(xmlTextAddress);
subRoot.AppendChild(address);
if (xmlDoc.DocumentElement != null)
xmlDoc.DocumentElement.AppendChild(subRoot);
var country= xmlDoc.CreateElement("Country");
var xmlTextCountry = xmlDoc.CreateTextNode(textBox5.Text.Trim());
country.AppendChild(xmlTextCountry);
subRoot.AppendChild(country);
if (xmlDoc.DocumentElement != null)
xmlDoc.DocumentElement.AppendChild(subRoot);
xmlDoc.Save(FileName);
if (File.Exists(FileName))
return;
var textWritter = new XmlTextWriter(FileName, null);
textWritter.WriteStartDocument();
textWritter.WriteStartElement("CustomerRecord");
textWritter.WriteEndElement();
textWritter.Close();
}
//Search by id or by Mobile
private void button3_Click(object sender, EventArgs e)
{
}
示例 XML:
<CustomerRecord>
<Customer id="6786">
<FirstName>khkjh</FirstName>
<LastName>jkhjkh</LastName>
<Mobile>887897</Mobile>
<Address>jk</Address>
<Country>fdgfdg</Country>
</Customer>
</CustomerRecord>