2017-03-04 130 views
2

我想檢查XML中的重複元素。請幫忙!C#:檢查XML中的重複元素

XML:

<?xml version="1.0" encoding="utf-8"?> 
<List> 
    <Email_Entry></Email_Entry> 
    <Email_Entry EmailID="[email protected]" /> 
    <Email_Entry EmailID="[email protected]" /> 
    <Email_Entry EmailID="[email protected]" /> 
    <Email_Entry EmailID="[email protected]" /> 
    <Email_Entry EmailID="[email protected]" /> 
</List> 

aspx.cs:

protected void btnEmailSubscribe_Click(object sender, EventArgs e) 
{    
    string EmailID = txtEmailSubscribe.Text; 
    string FILE_PATH = Server.MapPath("~/Logs/SubscribedEmails.xml"); 

    XDocument Emailxml = XDocument.Load(FILE_PATH); 
    var EmailExist = Emailxml.Descendants("Email_Entry") 
     .Any(x => (string)x.Element("EmailID") == txtEmailSubscribe.Text); 
    if (EmailExist) 
    { 
     lblEmail.Text = "EmailID already exist"; 
    } 
    else 
    { 
     Emailxml.Root.Add(new XElement("Email_Entry", 
        new XAttribute("EmailID", EmailID) 
       )); 
     Emailxml.Save(FILE_PATH); 
     lblEmail.Text = "Subscribed Successfully"; 
    }    
} 

回答

2

檢查屬性值,而不是元素:

var EmailExist = Emailxml.Descendants("Email_Entry") 
     .Any(x => x.Attribute("EmailID").Value == txtEmailSubscribe.Text); 
+0

應該在哪裏而不是任何。任何將返回true/false, – jdweng

+0

@jdweng當我檢查電子郵件存在我使用'任何' – Backs

+0

@Backs謝謝你的幫助!!!!!!! –

0

VAR XML = File.ReadAllText(「XML文件路徑「);

 var xmlDoc = new XmlDocument(); 
     xmlDoc.LoadXml(xml); 

     var dups = xmlDoc.FirstChild.ChildNodes 
      .Cast<XmlNode>() 
      .Where(n=>n.Attributes.Count>0) 
      .GroupBy(n => n.Attributes["EmailID"].Value) 
      .Where(g => g.Count() > 1) 
      .SelectMany(g => g.ToList()) 
      .ToList();