更新(订购)结果 XML:
<root>
<node value="110" />
<node value="111">
<node value="114" />
<node value="115">
<node value="120" />
<node value="121" />
</node>
</node>
<node value="112">
<node value="122">
<node value="130" />
<node value="131" />
</node>
</node>
</root>
我曾经考虑过这段代码中的顺序
XmlDocument doc = new XmlDocument();
int[] numArray = new int[] { 110, 111, 114, 115, 120, 121, 112, 122, 130, 131 };
XmlElement head = doc.CreateElement("root");
doc.AppendChild(head);
XmlElement cur = doc.CreateElement("node");
cur.SetAttribute("value", numArray[0].ToString());
head.AppendChild(cur);
int pos = 0;
BuildXml(numArray, ref pos, ref doc, head, cur);
和递归函数
public static void BuildXml(int[] numArray, ref int pos, ref XmlDocument doc, XmlElement parNode, XmlElement curNode)
{
if (pos < numArray.Length-1)
{
if (numArray[pos] + 1 == numArray[pos + 1])
{
XmlElement current = doc.CreateElement("node");
current.SetAttribute("value", numArray[pos + 1].ToString());
parNode.AppendChild(current);
pos++;
BuildXml(numArray, ref pos, ref doc, parNode, current);
}
else if (numArray[pos] < numArray[pos + 1])
{
XmlElement current = doc.CreateElement("node");
current.SetAttribute("value", numArray[pos + 1].ToString());
curNode.AppendChild(current);
pos++;
BuildXml(numArray, ref pos, ref doc, curNode, current);
}
else
{
XmlElement elem = null;
foreach (XmlElement nodes in doc.FirstChild.ChildNodes) GetNode(nodes, numArray[pos + 1], ref elem);
XmlElement current = doc.CreateElement("node");
current.SetAttribute("value", numArray[pos + 1].ToString());
((XmlElement)elem.ParentNode).AppendChild(current);
pos++;
BuildXml(numArray, ref pos, ref doc, ((XmlElement)elem.ParentNode), current);
}
}
}
public static void GetNode(XmlElement elem, int val, ref XmlElement found)
{
if (int.Parse(elem.GetAttribute("value")) < val)
if (found == null || int.Parse(found.GetAttribute("value")) < val) found = elem;
foreach (XmlElement childElem in elem.ChildNodes) GetNode(childElem, val, ref found);
}