Below code is the function to Append a customerRecord
in the Xml file.
I've got 2 questions here:
1.When I append a record, how to check whether the value of id
and Mobile
is already existing in the XML??
2.How to search a customer by id
or by Mobile
and display the values in the 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)
{
}
Sample XML:
<CustomerRecord>
<Customer id="6786">
<FirstName>khkjh</FirstName>
<LastName>jkhjkh</LastName>
<Mobile>887897</Mobile>
<Address>jk</Address>
<Country>fdgfdg</Country>
</Customer>
</CustomerRecord>