我有一个程序可以读取制表符分隔的文件并构建一个示例 xml 文件。
\t\t\troot
\t\t\t\tnode1
输出:
<root><node1></node1></root>
我想更改程序的逻辑以构建构建 xmldocument 的字符串表示形式,而不是 c# 构建 xmldocument 以实现自动化目的的 xml。
例如(文档的实际文本)
"XmlElement XElemRoot = xDoc.CreateElement("root");
XmlElement XElemSecond = xDoc.CreateElement("node1");
XElemRoot.AppendChild(XElemSecond);"
当前代码:
string[] files = System.IO.File.ReadAllLines(@"C:\dell\test\xmlsamplemaker\xmlsampler\xmlsampler\bin\Debug\textofxml.txt");
string newXml = string.Empty;string[] xmlHolder;
List<int> levels = new List<int>();
var lastlevel = 0;
Stack<String> stack = new Stack<String>();
for (int lines = 0; lines < files.Length; lines++) //start
{
var firstNode = files[lines].TrimEnd('\t');
levels.Add(TextTool.CountStringOccurrences(firstNode, "\t")); //first count
if (lines == 0)
{
newXml += "<" + files[lines].Replace("\t", "") + ">" + System.Environment.NewLine;
stack.Push(files[lines].Replace("\t", ""));
}
else{
if (levels[levels.Count - 1] == levels[levels.Count - 2])
{
newXml += "</" + stack.Pop() + ">" + System.Environment.NewLine;
newXml += "<" + files[lines].Replace("\t", "") + ">" +System.Environment.NewLine;
stack.Push(files[lines].Replace("\t", ""));
}
else if (levels[levels.Count - 1] > levels[levels.Count - 2])
{
newXml += "<" + files[lines].Replace("\t", "") + ">" + System.Environment.NewLine;
stack.Push(files[lines].Replace("\t", ""));
}
else
{
newXml += "</" + stack.Pop() + ">" + System.Environment.NewLine;
newXml += "</" + stack.Pop() + ">" + System.Environment.NewLine;
newXml += "<" + files[lines].Replace("\t", "") + ">" + System.Environment.NewLine;
stack.Push(files[lines].Replace("\t", ""));
}
}
}
var size = stack.Count;
for (int j = 0; j < size; j++)
{
newXml += "</" + stack.Pop() + ">" + System.Environment.NewLine;
}
System.IO.File.WriteAllText(@"C:\dell\xmlsample.xml", newXml);