我正在通过阅读示例制表符分隔的文档来构建代码自动化。我的 xml 文档结构已关闭。我的逻辑有什么问题?我看到两种情况来找到 xml 节点的正确父节点。
for (int lines = 0; lines < files.Length; lines++) //start
{
var firstNode = files[lines].TrimEnd('\t');
NodeNames.Add(files[lines].Replace("\t","") + lines);
levels.Add(TextTool.CountStringOccurrences(firstNode, "\t")); //first count
if (lines == 0)
{
newXml += "XmlNode " + NodeNames[lines] + "Node" + " = xmlDoc.CreateElement(\"" + files[lines].Replace("\t", "") + "\");" + System.Environment.NewLine;
//set value to empty
newXml += NodeNames[lines] + "Node" + ".InnerText = String.Empty;" + System.Environment.NewLine;
newXml += "xmlDoc.AppendChild(" + NodeNames[lines] + "Node);" + System.Environment.NewLine;
}
else{
if (levels[levels.Count - 1] > levels[levels.Count - 2])
{
//create new ele
newXml += "XmlNode " + NodeNames[lines] + "Node" + " = xmlDoc.CreateElement(\"" + files[lines].Replace("\t", "") + "\");" + System.Environment.NewLine;
//set value to empty
newXml += NodeNames[lines] + "Node" + ".InnerText = String.Empty;" + System.Environment.NewLine;
//add new ele as child to previous ele
newXml += NodeNames[lines - 1] + "Node" + ".AppendChild(" + NodeNames[lines] + "Node" + ");" + System.Environment.NewLine;
}
else
{
//create new ele
newXml += "XmlNode " + NodeNames[lines] + "Node" + " = xmlDoc.CreateElement(\"" + files[lines].Replace("\t", "") + "\");" + System.Environment.NewLine;
var lastSmallest = levels.Count - 1;
var current = levels[levels.Count - 1];
var checker = levels[levels.Count - 1];
while (checker >= current)
{
lastSmallest = lastSmallest - 1;
checker = levels[lastSmallest];
}
//set node value to empty;
newXml += NodeNames[lines] + "Node" + ".InnerText = String.Empty;" + System.Environment.NewLine;
newXml += NodeNames[checker] + "Node" + ".AppendChild(" + NodeNames[lines] + "Node" + ");" + System.Environment.NewLine;
}
}
}