简体   繁体   中英

Searching String to Xml file in C#

<AccessUrl>  
  <Url>/User/Index</Url>
  <Url>/EmailAccounts/Index</Url>
  <Url>/Registration/Index</Url>
</AccessUrl>  

I have a xml file. I wand to search a string in it. I have written a C# code for it.

 string Url="/User/Index";// or One of the above value from file. var CheckPermission = (from a in doc.Elements("AccessUrl") where a.Element("Url").Value.Contains(Url) select a).Any(); 

but it only works OK with first Url value from file. But if i change the string Url="/EmailAccounts/Index"; . It doesn't show any match even the url value exists in xml file.Well i tried a lot but didn't get succeed yet.

This is because a.Element("Url") gives you the first child element with specified name. You should go through all children instead with something like:

a.Elements("Url").Any(u => u.Value.Contains(Url))

This is because you are calling:

where a.Element("Url")

This will return the first matching element.

From the docs:

Gets the first (in document order) child element with the specified System.Xml.Linq.XName

You need to use something like this to check all elements:

var CheckPermission = (from a in doc.Descendants("Url")
                               where a.Value.Contains(Url)
                               select a).Any();

This appears to work.

        string url="/EmailAccounts/Index";// or One of the above value from file.
        var checkPermission = xml.Elements("AccessUrl").Elements("Url").Any(x => x.Value == url);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM