I've got a "flat" XML menu that I need to structure.
Current XML tree:
<root>
<nodes>
<node>
<id>5</id>
<parent>1</parent>
</node>
<node>
<id>8</id>
<parent>5</parent>
</node>
<node>
<id>14</id>
<parent>8</parent>
</node>
<node>
<id>26</id>
<parent>1</parent>
</node>
</nodes>
</root>
This XML tree need to be reodered to have correct relations between ID:s and ParentID:S
<root>
<nodes>
<node>
<id>5</id>
<parent>1</parent>
<node>
<id>8</id>
<parent>5</parent>
<node>
<id>14</id>
<parent>8</parent>
</node>
</node>
</node>
<node>
<id>26</id>
<parent>1</parent>
</node>
</nodes>
</root>
Iv got the following code to try to accomplish this:
public XmlDocument SortXmlNodeTree(XmlDocument udoc)
{
XmlDocument sortedDoc = new XmlDocument();
sortedDoc.LoadXml(xmlStartString);
//select top nodes
//top node -> find all siblings. For each sibling add sibling.siblings. ->loop
XmlNode nodes = udoc.DocumentElement.LastChild;
foreach(XmlNode n in nodes)
{
//get top nodes and check if they are folders
if (n["parent"].InnerText.Equals("1") && n["type"].InnerText.Equals("2"))
{
XmlNode newNode = sortedDoc.ImportNode(n, true);
GetNodeSiblings(ref nodes, newNode, ref sortedDoc);
SortedDoc.DocumentElement.FirstChild.AppendChild(newNode);
}
}
return sortedDoc;
}
public XmlNode GetNodeSiblings(ref XmlNode nodes, XmlNode currentNode, ref XmlDocument tree)
{
if (!nodes.HasChildNodes)
{
return null;
}
foreach (XmlNode n in nodes)
{
// if we have a folder and parent is currentNode, go deeper
if (n["type"].InnerText.Equals("2") && n["parent"].InnerText.Equals(currentNode["id"].InnerText))
{
XmlNode newNode = tree.ImportNode(n, true);
GetNodeSiblings(ref nodes, newNode, ref tree);
currentNode.AppendChild(newNode);
}
// if we have a product that has currentNode as parent, add it.
else if (!n["type"].InnerText.Equals("2") && n["parent"].InnerText.Equals(currentNode["id"].InnerText))
{
XmlNode newNode = tree.ImportNode(n, true);
nodes.RemoveChild(n);
currentNode.AppendChild(newNode);
}
}
return null;
}
As you can see my nodes also contain "type" and "name". Types are used to determine if a nodes is a "folder" or a "product".
My problem is that this dosn't return the correct XML. If I remove the nodes.RemoveChild(n) in the last section then it works great but I whant to remove the children (products, type=1) that I know haven't got any children.
If this code is run. I only get a few nodes.
Thx for any help!
Best Regards Marthin