Jon*_*way 2 c# xml linq-to-xml
我有两个文档 - 一个是自定义XML文件格式,另一个是带有一堆自定义扩展的RSS源.我希望在一个元素值匹配时使用RSS提要中的值填充XML文件中的字段.
这适用于将手动运行几次的脱机过程 - 它不需要执行良好,所有容错,等等.手动劳动或干预是好的.
我的主XML文档如下所示:
<videos>
<video>
<title>First Video</title>
<code>AAA123</code>
<id>decaf-decaf-decaf-decaf</id>
<description>lots of text here...</description>
</video>
<video>
<title>Second Video with no code</title>
<code></code>
<id>badab-badab-badab-badab</id>
<description>lots of text here...</description>
</video>
</videos>
Run Code Online (Sandbox Code Playgroud)
RSS提要是标准的RSS,有一些额外的字段:
<ns:code>AAA123</ns:code>
<ns:type>Awesome</ns:type>
<ns:group>Wonderful</ns:group>
Run Code Online (Sandbox Code Playgroud)
当__CODE__要__CODE__动态修改属性时,我想将RSS文档中的额外字段拉入XML文档,以报告需要几秒钟才能完成的过程.问题是在Firefox上,在脚本完成之前,页面实际上并未重新呈现以反映该更改.这使得应用程序感觉迟钝.有没有办法确保即使运行更多脚本,HTML的更改也会立即显示?
听起来像是LINQ to XML的工作!
var vidDoc = XDocument.Parse(vidXml);
var rssDoc = XDocument.Parse(rssXml);
var videos = vidDoc.XPathSelectElements("/videos/video");
var rssItems = rssDoc.XPathSelectElements("/rss/channel/item");
var matches = videos.Join(
rssItems,
video => video.Element(XName.Get("code")).Value,
rssItem => rssItem.Element(XName.Get("code", "http://test.com")).Value,
(video, item) => new {video, item});
foreach (var match in matches)
{
var children = match.item.Elements()
.Where(child => child.Name.NamespaceName == "http://test.com" &&
child.Name.LocalName != "code");
foreach (var child in children)
{
//remove the namespace
child.Name = XName.Get(child.Name.LocalName);
match.video.Add(child);
}
}
vidDoc.Save(Console.Out);
Run Code Online (Sandbox Code Playgroud)
上面的解决方案假设RSS文档看起来像这样:
<rss xmlns:ns="http://test.com" version="2.0">
<channel>
<item>
<title>AAA123</title>
<link>http://test.com/AAA123</link>
<pubDate>Sun, 26 Jul 2009 23:59:59 -0800</pubDate>
<ns:code>AAA123</ns:code>
<ns:type>Awesome</ns:type>
<ns:group>Wonderful</ns:group>
</item>
</channel>
</rss>
Run Code Online (Sandbox Code Playgroud)