[英]Parse XML with Linq according to 2 values
I would like to know how to parse my xml file in c# with LinQ, I made a lot of research but there isn't my precise case.. 我想知道如何使用LinQ在c#中解析我的xml文件,我做了很多研究,但没有确切的案例。
So here is my xml code : 所以这是我的xml代码:
<WindowsMediaPlayer>
<Playlist name="playlistdefouf">
<Element>
<type>Audio</type>
<name>lol</name>
</Element>
<Element>
<type>Video</type>
<name>tamere</name>
</Element>
</Playlist>
</WindowsMediaPlayer>
I would like to make a function that verify if a song exists (With type AND name) according to the right playlist too. 我也想做一个函数来根据正确的播放列表来验证一首歌曲是否存在(类型为AND名称)。
For example if I got in parameters playlistname = "playlistdefouf",type = "Audio" and name = "lol" my function will return 1 例如,如果输入参数playlistname =“ playlistdefouf”,type =“ Audio”,name =“ lol”,我的函数将返回1
I already tried to do something but I think I'm lost.. 我已经尝试过做某事,但我认为我迷路了。
XDocument xmlFile = XDocument.Load(Helper.xmlFolder + "/playlist.xml");
IEnumerable<XElement> elem = xmlFile.Root.Descendants();
IEnumerable<XElement> requete = from d in elem
where d.Name == "Playlist"
&& d.Attribute("name").Value == "playlistdefouf"
select d;
IEnumerable<XElement> requete2 = from d in requete.Descendants()
where d.Name == "Element"
select d;
IEnumerable<XElement> requete3 = from d in requete2.Descendants()
select d;
Here is how to retrieve an IEnumerable of the Playlists that have a specific type and name: 以下是如何检索具有特定类型和名称的IEnumerable播放列表的方法:
XDocument xmlFile = XDocument.Load("playlists.xml");
var res = from playlist in xmlFile.Root.Elements("Playlist")
where
playlist.Attribute("name").Value == "playlistdefouf" &&
playlist.Element("Element").Element("type").Value == "Audio" &&
playlist.Element("Element").Element("name").Value == "lol"
select playlist;
You can get a count of the playlists by using the Count()
extension method 您可以使用
Count()
扩展方法来获得播放列表的Count()
res.Count();
Or you can use the Extension method Any()
instead of Count to get a boolean that is more expressive if you want to know if a list contains any elements matching your parameters. 或者,如果您想知道列表是否包含任何与参数匹配的元素,则可以使用Extension方法的
Any()
代替Count来获得更具表现力的布尔值。
This yields the same result but I personally prefer it structured this way: 这会产生相同的结果,但我个人更喜欢这种结构:
var xml = XDocument.Load("playlist.xml");
var result = from playlist in xml.Descendants("Playlist")
where (string)playlist.Attribute("name") == "playlistdefouf"
from song in playlist.Descendants("Element")
where (string)song.Element("type") == "Audio" && (string)song.Element("name") == "lol"
select playlist;
Then you can use the IEnumerable extensions to get the results you want: 然后,您可以使用IEnumerable扩展来获得所需的结果:
var count = result.Count();
var isExisting = result.Any();
var playlist = result.ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.