0
我下面的兩個XML:XLINQ:從一個XML元素複製到其他
A.XML
<contacts>
<contact>
<name>Patrick Hines</name>
<phone type="home">206-555-0144</phone>
</contact>
</contacts>
B.XML
<contacts>
<contact>
<name>Patrick Hines</name>
<phone type="home">206-555-0144</phone>
<phone type="work">425-555-0145</phone>
<address>
<street1>123 Main St</street1>
<city>Mercer Island</city>
</address>
</contact>
<contact>
<name>Gretchen Rivas</name>
<phone type="mobile">206-555-0163</phone>
<DOB>10/10/87</DOB>
<address>
<state>WA</state>
<postal>68042</postal>
</address>
</contact>
</contacts>
B. xml有以下增加:
- 元素地址已添加。
- 又增加了一個聯繫人,其中添加了一個新元素DOB。
問題:
我想列出新添加的元素,但不是所有的子元素。
另外我想複製新添加的元素從B到A使用XLinq和連接。
有什麼辦法嗎?
我嘗試以下操作:
void test()
{
XDocument aDoc = XDocument.Load("A.xml");
XDocument bDoc = XDocument.Load("B.xml");
string allGroups = string.Empty;
string newElementsInGroup = "\n";
List<string> ignoreGroups = new List<string>(new string[] { "SkipThisGroup1", "SkipThisGroup2"});
foreach (XElement groupElement in bDoc.Descendants("contacts").ToList())
{
//I've not displayed this in above xml
if (ignoreGroups.Contains(groupElement.Element("Name").Value))
{
continue;
}
string groupName = groupElement.Element("Name").Value;
// Get same group from A.xml
IEnumerable<XElement> groupsInADoc = (from c in aDoc.Descendants("Contacts")
where (string)c.Element("Name").Value == groupName
select c);
// Proceed if group is found
if (groupsInADoc != null && groupsInADoc.Count() > 0)
{
XElement groupInA = groupsInADoc.First();
// Each group has count element, which is again not displayed in above xml
int aGroupCount = Convert.ToInt32(groupInA.Element("Cnt").Value);
int bGroupCount = Convert.ToInt32(groupElement.Element("Cnt").Value);
// If count of child elements in A group is less than that of B group, find the newly added group.
if (aGroupCount < bGroupCount)
{
allGroups = string.Concat(allGroups, " ", groupName);
IEnumerable<XElement> newElements = groupElement.Elements().Except(groupInA.Elements());
newElementsInGroup = "New elements in group " + groupName + " are : ";
foreach (XElement item in newElements)
{
newElementsInGroup += (item.Element("Name").Value + " ");
}
}
newElementsInGroup += "\n";
}
}
MessageBox.Show(allGroups + newElementsInGroup, "Groups that have additional members");
}
我已經使用我的試用代碼編輯了該問題。請看一看。 –
這段代碼有什麼問題? –
以下聲明爲我提供了具有價值差異的所有內容,而我想列出新元素,而不是其子元素:IEnumerable newElements = groupElement.Elements()。除(groupInA.Elements()); –