下面的代碼是在Xml文件中追加customerRecord
的函數。 我在這裏有2個問題:驗證XML中的重複值
1.當我追加一條記錄時,如何檢查id
和Mobile
的值是否已經存在於XML?
2.如何通過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>
:你能給我任何建議繼續我的問題? – linguini 2012-08-09 07:20:10