我有两个文档 - 一个是自定义 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>
RSS feed 是带有一些额外字段的标准 RSS:
<ns:code>AAA123</ns:code>
<ns:type>Awesome</ns:type>
<ns:group>Wonderful</ns:group>
当 值与以下值匹配时,我想将额外字段从 RSS 文档提取到 XML 文档中:
<videos>
<video>
<title>First Video</title>
<code>AAA123</code>
<id>decaf-decaf-decaf-decaf</id>
<description>lots of text here...</description>
<type>Awesome</type>
<group>Wonderful</group>
</video>
<video>
<title>Second Video with no code</title>
<code></code>
<id>badab-badab-badab-badab</id>
<description>lots of text here...</description>
<type></type>
<group></group>
</video>
</videos>
我最喜欢使用 C#、LINQ 或某种 Excel-fu。我想如果必须的话我可以处理 XSLT,只要它不涉及我自己编写太多 XSLT。
我看了这个问题,但它似乎对我想做的事情没有多大帮助: Merge XML documents
最佳答案
听起来像是 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);
上述解决方案假设 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>
关于c# - XML 文档的松散合并,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1209656/