【发布时间】:2017-05-23 17:04:26
【问题描述】:
在这个 LINQ 查询中,我正在为我自己的 CD 创建一个带有轨道对象的新 XDocument:
var cdXml = new XDocument(new XElement("CD", new XAttribute("Artiest", c.Titel), new XAttribute("Naam", c.Naam),
from t in c.tracks
select new XElement("Tracks",
new XElement("Track"),
new XElement("Artiest", t.Artiest),
new XElement("Titel", t.Titel),
new XElement("Lengte", t.Lengte)
)));
我正在使用来自音乐网站的 API,这就是我从中创建第二个 XDocument 的方式:
String xmlString;
using (WebClient wc = new WebClient())
{
xmlString = wc.DownloadString(@"http://link-to-method");
}
XDocument myXMLDoc = XDocument.Parse(xmlString);
之后,我想将 myXMLDoc 中的曲目添加到我自己的 cdXml 文档中,我已经向 cdXml 文档中添加了 3 个曲目,我只想添加 myXMLDoc 中尚未出现在我的 cdXml 文档中的曲目。
这是我的查询,但它不起作用:
var query1 = from track in cdXml.Root.Elements("Tracks")
from track2 in myXMLDoc.Root.Element("album").Element("tracks").Elements("track")
where !track2.Element("name").Value.Contains(track.Element("Titel").Value)
select cdXml.Element("Tracks").Add(new XElement("Artiest", track2.Element("name").Value),
new XElement("Titel", track2.Element("artist").Element("name").Value),
new XElement("Lengte", track2.Element("duration").Value));
如何将 myXMLDoc 中的现有元素添加到我的 cdXml?
这是来自 2 个轨道的 API 调用的 xml 文件:
<lfm status="ok">
<album>
<name>Awake</name>
<artist>Dream Theater</artist>
<mbid>e5544c68-43e9-4754-9239-b618454557f4</mbid>
<url>https://www.last.fm/music/Dream+Theater/Awake</url>
<image size="small">https://lastfm-img2.akamaized.net/i/u/34s/96e5ac5821bf4a138aec1b8f80f25a6f.png</image>
<listeners>216679</listeners>
<playcount>6046178</playcount>
<tracks>
<track rank="1">
<name>6:00</name>
<url>https://www.last.fm/music/Dream+Theater/_/6:00</url>
<duration>331</duration>
<streamable fulltrack="0">0</streamable>
<artist>
<name>Dream Theater</name>
<mbid>28503ab7-8bf2-4666-a7bd-2644bfc7cb1d</mbid>
<url>https://www.last.fm/music/Dream+Theater</url>
</artist>
</track>
<track rank="2">
<name>Caught in a Web</name>
<url>https://www.last.fm/music/Dream+Theater/_/Caught+in+a+Web</url>
<duration>328</duration>
<streamable fulltrack="0">0</streamable>
<artist>
<name>Dream Theater</name>
<mbid>28503ab7-8bf2-4666-a7bd-2644bfc7cb1d</mbid>
<url>https://www.last.fm/music/Dream+Theater</url>
</artist>
</track>
</album>
</lfm>
我终于找到了自己的解决方案:
var query = from track in myXMLDoc.Root.Element("album").Element("tracks").Elements("track")
join track2 in cdXml.Root.Elements("Tracks") on track.Element("name").Value equals track2.Element("Titel").Value into joinedT
from track2 in joinedT.DefaultIfEmpty()
where track2 == null
select track;
【问题讨论】:
-
"它不工作:" -- 你希望该代码做什么,它会做什么?
-
我想将 myXMLDoc 中的 xml 元素(艺术家、姓名、持续时间)添加到 cdXml 文档中,以便它会添加:
Dream Theater 标记和内容。 -
它做了什么?
标签: c# xml linq linq-to-xml