【问题标题】:C# LINQ use xml with case insensitive queriesC# LINQ 使用 xml 和不区分大小写的查询
【发布时间】:2016-12-06 15:11:43
【问题描述】:

我尝试使用将遍历 xml 文档的 LINQ 查询。但是我想使用 OR 语句或 string.toLower() 来确保它总是能得到它需要的数据

我目前有:

// read all <item> tags and put the in an array.
XDocument xml = XDocument.Parse(xmlData);
var newItems = (from story in xml.Descendants("item")
    select new Feed
    {
        Title = ((string) story.Element("title")),
            Link = ((string) story.Element("link")),
            Description = ((string) story.Element("description")),
            PublishDate = ((string) story.Element("pubDate")),
    }
).Take(20).ToList();

我还想改变什么:

  1. (例如)Title = ((string)story.Element("title")) 需要不区分大小写。
  2. from story in xml.Descendants("item") select new Feed 需要在项目和条目中搜索(均不区分大小写)。

PS:当我正在遍历 RSS 文档时,我无法直接访问 XML 文档。

感谢您的意见。

【问题讨论】:

  • "((string)story.Element("title")) 需要不区分大小写" 这是否意味着您的 xml 中有 titleTitle?我不明白您所说的搜索不区分大小写是什么意思。
  • @HimBromBeere,无论是标题还是标题,它都会返回相同的结果。

标签: c# xml linq


【解决方案1】:

您可以为此创建扩展方法。这是我通常使用的类:

public static class XElementExtensions {
    public static bool EqualsIgnoreCase(this XName name1, XName name2) {
        return name1.Namespace == name2.Namespace &&
            name1.LocalName.Equals(name2.LocalName, StringComparison.OrdinalIgnoreCase);
    }

    public static XElement GetChild(this XElement e, XName name) {
        return e.EnumerateChildren(name).FirstOrDefault();
    }

    public static IEnumerable<XElement> EnumerateChildren(this XElement e, XName name) {
        return e.Elements().Where(i = > i.Name.EqualsIgnoreCase(name));
    }
}

然后,您可以将代码更改为以下内容:

var newItems = (from story in xml.Root.EnumerateChildren("item")
select new Feed
{
    Title = ((string) story.GetChild("title")),
        Link = ((string) story.GetChild("link")),
        Description = ((string) story.GetChild("description")),
        PublishDate = ((string) story.GetChild("pubDate")),
}).Take(20).ToList();

【讨论】:

    【解决方案2】:

    XML 通常由模式定义 - 它应该具有元素名称的固定格式 - 所以title 与 XML 术语中的 TiTlE 相同。我认为使用 .Element 做你想做的事是不可能的

    【讨论】:

    • 是的,我发现尽管不同的 RSS 有不同的时间表,所以我想而不是进行 3 次查询,我会看看是否有人找到了解决方案。
    • 可能有办法做到这一点 - 例如在开始之前将所有 XML 标记转换为大写。例如stackoverflow.com/questions/9334771/…
    猜你喜欢
    • 1970-01-01
    • 2019-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-18
    相关资源
    最近更新 更多