這裏有一個棘手的問題。比較兩個xmlfiles,添加缺少的元素
我得到了一個文件,MainFile.XML看起來像這樣:
<xml>
<header>
<some></some>
<addThis></addThis>
</header>
<footer></footer>
<this>
<is>
<deep>
<like></like>
</deep>
</is>
</this>
<test></test>
<page></page>
<addThis></addThis>
而我的其他文件,LangFile.XML看起來是這樣的。
<xml>
<header>
<some>English file</some>
</header>
<footer>Footer</footer>
<this>
<is>
<deep>
<like>Hey</like>
</deep>
</is>
</this>
<test>Something</test>
</xml>
我想,這樣是我MainFile.XML匹配來更新我的LangFile.XML但我需要把所有的文本值在LangFile。
我想LangFile看起來像這樣的更新之後: 預期產出
<xml>
<header>
<some>English file</some>
<addThis></addThis>
</header>
<footer>Footer</footer>
<this>
<is>
<deep>
<like>Hey</like>
</deep>
</is>
</this>
<test>Something</test>
<page></page>
<addThis></addThis>
</xml>
我看了這個答案,但我需要更新文件,並保留值... Compare two text files line by line
棘手的部分是嵌套,也可以是在1級到X級深什麼...
我的問題是,I D ont知道如何逐行比較行中的樹時,我嘗試了這樣的東西,但我堅持...我不知道如何將特定的後代添加到新的列表。
String directory = @"C:\Utv\XmlTest";
var mainFile = XDocument.Load(Path.Combine(directory, "MainFile.XML"));
var langFile = XDocument.Load(Path.Combine(directory, "LangFile.XML"));
//Get all descendant nodes
var mainFileDesc = mainFile.Root.Descendants().ToList();
var langFileDesc = langFile.Root.Descendants().ToList();
//Loop through the mainfile
for(var i = 0; i < mainFileDesc.Count(); i++)
{
var mainRow = mainFileDesc[i];
var langRow = langFileDesc[i];
//Compare the rows descendants, if not the same, add the mainRow to the langRow
if(mainRow.Descendants().Count() != langRow.Descendants().Count())
{
//Here I want to check if the mainRow != the langRow
//if not, add the mainRow to the langFile list
if(mainRow != langRow)
{
langFileDesc.Insert(i, mainRow);
}
}
}
即時得到下面的錯誤現在:
var langRow = langFileDesc[i];
Message Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index
這是因爲清單不具有相同的長度,這就是爲什麼我需要將其添加到列表...
可以有多少物品?多少嵌套?任何ID值?如果當兩個文本值不一致? –
mainfile永遠不會有任何文本值。嵌套是靈活的,它可以是1 -1000之間的任何水平... – JOSEFtw
1000個關卡?你不應該在那裏使用XML,你可能在這裏看一個遞歸的解決方案。 –