简体   繁体   English

在C#中将字符串搜索到Xml文件

[英]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. 我有一个xml文件。 I wand to search a string in it. 我想在其中搜索一个字符串。 I have written a C# code for it. 我已经为此编写了C#代码。

 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"; 但是,如果我更改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. 即使url值存在于xml文件中也没有显示任何匹配。好吧,我尝试了很多,但没有成功。

This is because a.Element("Url") gives you the first child element with specified name. 这是因为a.Element("Url")为您提供了具有指定名称的第一个子元素。 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 获取具有指定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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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