private static void UpdateExistingElementsAndAttribsRecurse(XmlNodeList fromNodes, XmlNode toParentNode)
{
int iSameElement = 0;
XmlNode lastElement = null;
foreach (XmlNode node in fromNodes)
{
if (node.NodeType != XmlNodeType.Element)
{
continue;
}
if (lastElement != null
&& node.Name == lastElement.Name && node.NamespaceURI == lastElement.NamespaceURI)
{
iSameElement++;
}
else
{
iSameElement = 0;
}
lastElement = node;
XmlNode toNode;
if (node.Attributes["key"] != null)
{
toNode = SelectSingleNodeMatchingNamespaceURI(toParentNode, node, node.Attributes["key"] );
}
else if (node.Attributes["name"] != null)
{
toNode = SelectSingleNodeMatchingNamespaceURI(toParentNode, node, node.Attributes["name"] );
}
else if (node.Attributes["type"] != null)
{
toNode = SelectSingleNodeMatchingNamespaceURI(toParentNode, node, node.Attributes["type"] );
}
else
{
toNode = SelectSingleNodeMatchingNamespaceURI(toParentNode, node, iSameElement);
}
if (toNode == null)
{
if (node == null)
{
throw new ApplicationException("node == null");
}
if (node.Name == null)
{
throw new ApplicationException("node.Name == null");
}
if (toParentNode == null)
{
throw new ApplicationException("toParentNode == null");
}
if (toParentNode.OwnerDocument == null)
{
throw new ApplicationException("toParentNode.OwnerDocument == null");
}
Debug.WriteLine("app: " + toParentNode.Name + "/" + node.Name);
if (node.ParentNode.Name != toParentNode.Name)
{
throw new ApplicationException("node.ParentNode.Name != toParentNode.Name: " + node.ParentNode.Name + " !=" + toParentNode.Name);
}
try
{
toNode = toParentNode.AppendChild(toParentNode.OwnerDocument.CreateElement(node.Name) );
}
catch (Exception ex)
{
throw new ApplicationException("ex during toNode = toParentNode.AppendChild(: " + ex.Message);
}
}
//Copy element content if any
XmlNode textEl = GetTextElement(node);
if (textEl != null)
{
toNode.InnerText = textEl.InnerText;
}
//Copy attribs if any
foreach (XmlAttribute attrib in node.Attributes)
{
XmlAttribute toAttrib = toNode.Attributes[attrib.Name];
if (toAttrib == null)
{
Debug.WriteLine("attr: " + toNode.Name + "@" + attrib.Name);
toAttrib = toNode.Attributes.Append(toNode.OwnerDocument.CreateAttribute(attrib.Name));
}
toAttrib.InnerText = attrib.InnerText;
}
((XmlElement) toNode).IsEmpty = ! toNode.HasChildNodes; //Ensure no endtag when not needed
UpdateExistingElementsAndAttribsRecurse(node.ChildNodes, toNode);
}
}