I am trying to create an XML document as output using C# with the parent node being based on the count of tabs from the input file. I am trying to use XPath to determine the parent node. I have read the source file in and saved it as a list, and I am able to get the parts of the data saved as the attributes that I need, but the child nodes are not in the expected order. It is putting them in the expected "level", but not under the correct parent. My XPath seems to not be getting the parent that I expect it to, but I am not sure what is wrong with the XPath. It seems to work down to Filename8 (in the example), but it would put Filename9 under Filename 7 and then Filename8 would be found lower down in the tree. Of course this is a small sample of the input file, but I hope you will understand what I am trying to do. Any suggestions would be greatly appreciated!
Here is part of my code:
for (int i = 0; i < lines.Count; i++)
{
if (lines[i].StartsWith("/*"))
{
continue;
}
tabCount = 0;
tabCount = lines[i].Count(c => c == '\t');
if (lines[i].Contains("/*"))
{
titleIndex = lines[i].IndexOf("/*");
endTitleIndex = lines[i].IndexOf("*/");
title = lines[i].Substring(titleIndex + 2, endTitleIndex - titleIndex - 2).Trim();
}
else
{
titleIndex = lines[i].Length;
}
filename = lines[i].Substring(0, titleIndex).Trim();
XmlElement tocEntry = doc.CreateElement("tocEntry");
tocEntry.SetAttribute("filename", filename);
if (title.Length > 0)
{
tocEntry.SetAttribute("title", title);
}
tocEntry.SetAttribute("tabCount", tabCount.ToString());
if (tabCount == 0)
{
root.AppendChild(tocEntry);
}
else
{
XmlNode parent = root.SelectSingleNode("//tocEntry[@tabCount='" + (tabCount - 1) + "'][last()]");
parent.AppendChild(tocEntry);
}
}
Here is a small sample of the input file:
..\filename1.xml /* TITLE 1 */
/t..\filename2.xml /* TITLE 2 */
/t/t..\filename3.xml /* TITLE 3 */
/t/t..\filename4.xml /* TITLE 4 */
/t/t..\filename5.xml /* TITLE 5 */
/t/t..\filename6.xml /* TITLE 6 */
/t/t..\filename7.xml /* TITLE 7 */
/t..\filename8.xml /* TITLE 8 */
/t/t..\filename9.xml /* TITLE 9 */
/t/t/t..\filename10.xml /* TITLE 10 */
/t/t/t/t..\filename11.xml /* TITLE 11 */
Desired output sample:
<Entry filename="..\filename1.xml" title="TITLE 1">
<Entry filename="..\filename2.xml" title="TITLE 2">
<Entry filename="..\filename3.xml" title="TITLE 3"/>
<Entry filename="..\filename4.xml" title="TITLE 4"/>
<Entry filename="..\filename5.xml" title="TITLE 5"/>
<Entry filename="..\filename6.xml" title="TITLE 6"/>
<Entry filename="..\filename7.xml" title="TITLE 7"/>
</Entry>
<Entry filename="..\filename8.xml" title="TITLE 8">
<Entry filename="..\filename9.xml" title="TITLE 9">
<Entry filename="..\filename10.xml" title="TITLE 10">
<Entry filename="..\filename11.xml" title="TITLE 11"/>
</Entry>
</Entry>
</Entry>
</Entry>