2016-12-06 89 views
2

我試圖使用LINQ查詢來遍歷xml文檔。不過,我想無論是使用OR語句或string.toLower(),以確保它總是會得到的數據,它需要C#LINQ在不區分大小寫的查詢中使用xml

我目前有:

// 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. (EG)Title = ((string)story.Element("title"))需要搜索不區分大小寫。
  2. from story in xml.Descendants("item") select new Feed需要在項目中以及在條目中搜索(不區分大小寫)。

PS:當我遍歷RSS文檔時,我無法直接訪問XML文檔。

感謝您的輸入。

+0

「'((串)story.Element(」 標題「))'需要搜索案例insansitive「這是否意味着你的xml中有'title'和'Title'?我不明白你的意思是不區分大小寫。 – HimBromBeere

+0

[C#中大小寫不敏感的XML解析器]的可能重複(http://stackoverflow.com/questions/9334771/case-insensitive-xml-parser-in-c-sharp) – simonalexander2005

+0

@HimBromBeere,無論其標題或TiTle返回相同的結果。 –

回答

2

可以跳投創建爲擴展方法。下面是我通常使用類:

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

XML通常由模式定義的 - 它應該有元素名的固定格式 - 所以title一樣XML術語TiTlE。我不認爲這是可能做到你想要什麼,用.Element

+0

是的,我發現,不過不同的RSS有不同的時間表,所以沒有做出3個查詢,我會看看是否有人曾經找到過解決方案。 –

+0

可能有辦法做到這一點 - 例如在開始之前將所有的XML標籤轉換爲大寫。例如http://stackoverflow.com/questions/9334771/case-insensitive-xml-parser-in-c-sharp – simonalexander2005