避免在xml文件c#中重复输入

时间:2021-10-09 19:19:27

I am trying to restrict duplicate entry to an XML file and below is the XML file.

我试图限制对XML文件的重复输入,下面是XML文件。

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

Now if I try to add Ryan or Danny again to the ID I should alert like user name already exists.

现在,如果我尝试再次将Ryan或Danny添加到ID中,我应该像用户名已经存在一样发出警报。

I'm using the below code and it doesn't work. strName is a string and has username value to be added. Can anyone provide suggestions?

我正在使用下面的代码,但它不起作用。strName是一个字符串,并具有要添加的用户名值。任何人都可以提供建议吗?

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

2 个解决方案

#1


1  

Try this way:

试试这种方法:

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

The problem with your code is that it tries to access attribute ID. But ID is in fact another XML element contained inside element <Details>.

代码的问题在于它试图访问属性ID,但ID实际上是元素

中包含的另一个XML元素。

#2


0  

You could set ID as an attribute of Details and then check if that entry exist using the XmlDocument method GetElementByID, or implement a for cycle that checks out the property InnerText of every element in the array resulting from the call to GetElementsByName method.

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

#1


1  

Try this way:

试试这种方法:

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

The problem with your code is that it tries to access attribute ID. But ID is in fact another XML element contained inside element <Details>.

代码的问题在于它试图访问属性ID,但ID实际上是元素

中包含的另一个XML元素。

#2


0  

You could set ID as an attribute of Details and then check if that entry exist using the XmlDocument method GetElementByID, or implement a for cycle that checks out the property InnerText of every element in the array resulting from the call to GetElementsByName method.

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