2013-10-02 145 views
2

我有相同類型的2 XML元素(來自不同的XML文檔具有相同的架構)看起來像這樣:在C#相同類型的合併XML節點

<Parent> 
    <ChildType1>contentA</ChildType1> 
    <ChildType2>contentB</ChildType2> 
    <ChildType3>contentC</ChildType3> 
</Parent> 

<Parent> 
    <ChildType1>contentD</ChildType1> 
    <ChildType3>contentE</ChildType3> 
</Parent> 

元素類型ChildType1,ChildType2和ChildType3可以具有父元素中最多隻有一個實例。

我需要做的是與第一父節點的第二父節點的內容到一個新的節點,將這個樣子合併:

<Parent> 
    <ChildType1>contentD</ChildType1> 
    <ChildType2>contentB</ChildType2> 
    <ChildType3>contentE</ChildType3> 
</Parent> 
+1

您不希望第二個節點複製到第一個,要覆蓋第一與第二。或者你的樣本結果是錯誤的。 –

+0

覆蓋節點意味着結果將不包含元素。但我同意,複製也不是那裏最好的術語。 – vicch

回答

3

使用LINQ到XML解析源文件。然後按照元素名稱在它們和組之間創建一個聯合,並根據您想要的使用組中的第一個/最後一個元素創建一個新文檔。

事情是這樣的:

var doc = XElement.Parse(@" 
    <Parent> 
     <ChildType1>contentA</ChildType1> 
     <ChildType2>contentB</ChildType2> 
     <ChildType3>contentC</ChildType3> 
    </Parent> 
"); 

var doc2 = XElement.Parse(@" 
    <Parent> 
     <ChildType1>contentD</ChildType1> 
     <ChildType3>contentE</ChildType3> 
    </Parent> 
"); 

var result = 
    from e in doc.Elements().Union(doc2.Elements()) 
    group e by e.Name into g 
    select g.Last(); 
var merged = new XDocument(
    new XElement("root", result) 
); 

merged現在包含

<root> 
    <ChildType1>contentD</ChildType1> 
    <ChildType2>contentB</ChildType2> 
    <ChildType3>contentE</ChildType3> 
</root> 
+0

謝謝,它的工作! – vicch

1

如果命名兩個初始文檔作爲xd0xd1那麼這個工作對我來說:

var nodes = 
    from xe0 in xd0.Root.Elements() 
    join xe1 in xd1.Root.Elements() on xe0.Name equals xe1.Name 
    select new { xe0, xe1, }; 

foreach (var node in nodes) 
{ 
    node.xe0.Value = node.xe1.Value; 
} 

我得到這個結果:

<Parent> 
    <ChildType1>contentD</ChildType1> 
    <ChildType2>contentB</ChildType2> 
    <ChildType3>contentE</ChildType3> 
</Parent> 
+0

感謝您的回答,它的工作,但我發現了Mikael的回答有點清晰 – vicch

+1

@vicch - 這很好,但你的問題並要求更換節點的第一個XML,而不是創建一個完全新的文檔。我會認爲我的技術更精確? – Enigmativity

+0

你是對的,我編輯了這個問題。希望它更接近我現在想要的。 – vicch