【问题标题】:Avoid duplicate entry in xml file c#避免在xml文件c#中重复输入
【发布时间】:2017-03-04 13:51:29
【问题描述】:

我正在尝试将重复条目限制为 XML 文件,下面是 XML 文件。

<?xml version="1.0" standalone="yes"?>
<Info>
<Details>
<ID>Ryan</ID>
</Details>
<Details>
<ID>Danny</ID>
</Details>
</Info>

现在,如果我尝试再次将 Ryan 或 Danny 添加到 ID,我应该会提醒用户名已经存在。

我正在使用下面的代码,但它不起作用。 strName 是一个字符串,需要添加用户名值。谁能提供建议?

XDocument xDoc = XDocument.Load(Server.MapPath("~/Info.xml"));
bool userExistsAlready = xDoc.Descendants("Details").Any(x => (string)x.Attribute("ID") == strName);
if (userExistsAlready)
{
    //alert
}

【问题讨论】:

    标签: c# asp.net .net xml linq


    【解决方案1】:

    试试这个方法:

    bool userExistsAlready = xDoc.Descendants("Details")
                                 .Elements("ID")
                                 .Any(x => x.Value == "Ryan");
    

    您的代码的问题在于它试图访问 attribute ID。但ID 实际上是包含在元素&lt;Details&gt; 中的另一个XML 元素。

    【讨论】:

    • 如何检查另一个名为 department 的元素和条件。我尝试了几个代码,但无法得到它。
    • bool usertExists = xDocss.Descendants("Details").Elements("ID").Any(x => x.Value == Name) && xDocss.Descendants("Details").Elements ("密码").Any(y => y.Value == Pwd);
    • @vicky 好吧,这是另一个问题。不鼓励在 cmets 中回答问题。尝试使用相关的 XML 文件写一篇不同的文章。
    • 我已经习惯了,肯定会发布新的。
    【解决方案2】:

    您可以将 ID 设置为 Details 的一个属性,然后使用 XmlDocument 方法 GetElementByID 检查该条目是否存在,或者实现一个 for 循环,该循环检查由调用 GetElementsByName 方法产生的数组中每个元素的属性 InnerText。

    【讨论】:

      猜你喜欢
      • 2015-04-25
      • 2020-11-09
      • 2011-08-27
      • 2013-09-05
      • 2017-02-12
      • 2021-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多