小工具以 XML 為儲存媒介,需比對 cacheFile (來源) 與 mappingFile (目標),將來源中存在但目標缺失的 mapping 節點自動補齊。
if (File.Exists(cacheFile))
{
XDocument cacheDoc = XDocument.Load(cacheFile);
var query = from p in cacheDoc.Descendants("file")
where p.Attribute("blogId").Value == SourceBlog
select new
{
PostId = p.Attribute("postId").Value,
PostName = p.Attribute("name").Value.Replace("'", "")
};
XDocument mappingDoc = XDocument.Load(mappingFile);
foreach (var item in query)
{
// 若 mappingFile 中不存在相同 s/p/t 組合則新增
if (!mappingDoc.Descendants("mapping").Any(m =>
m.Attribute("s").Value == "SourceBlog" &&
m.Attribute("p").Value == item.PostId &&
m.Attribute("t").Value == "Target"))
{
mappingDoc.Element("mappings").Add(
new XElement("mapping",
new XAttribute("s", "SourceBlog"),
new XAttribute("p", item.PostId),
new XAttribute("t", "Target")
));
}
}
mappingDoc.Save(mappingFile);
}
Descendants("file"):遞迴查找所有 <file> 元素。Attribute("name").Value:取得屬性值。Any(predicate):高效判斷序列中是否存在符合條件元素。Element("mappings").Add(...):在根節點下新增子元素。