3

I was trying to use a LINQ query that will iterate through an xml document. However I wanted to either use an OR statement or a string.toLower() to make sure it will always get the data it needs

I currently have:

// 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();

what I still want to change:

  1. (E.G.) Title = ((string)story.Element("title")) needs to search case insensitive.
  2. from story in xml.Descendants("item") select new Feed needs to search in item as well as in entry (both case-insensitive).

PS: as I am iterating through the an RSS document I cannot directly access the XML document.

thanks for input.

Ian H.
  • 3,840
  • 4
  • 30
  • 60
Rodney Wormsbecher
  • 897
  • 2
  • 17
  • 39

2 Answers2

2

You can aways create extension methods for that. Here is the class that I normally use:

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));
    }
}

Then, you can change your code to something like this:

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();
Aldinei Sampaio
  • 221
  • 2
  • 4
0

XML is typically defined by a schema - it should have a fixed format for the element names - so title isn't the same as TiTlE in XML terms. I don't think it's possible to do what you want, using .Element

simonalexander2005
  • 4,338
  • 4
  • 48
  • 92
  • yes I found that as well however different RSS have different schedules so thought instead of making 3 queries, I'll see whether anyone has ever found a solution to this. – Rodney Wormsbecher Dec 06 '16 at 15:18
  • There probably are ways to do it - e.g. convert all of the XML tags to upper-case before starting. e.g. http://stackoverflow.com/questions/9334771/case-insensitive-xml-parser-in-c-sharp – simonalexander2005 Dec 06 '16 at 15:25