我正在尝试使用 C# 和 XmlTextWriter 解析下面提供的 XML 文件
例子:
<ChessBoard>
<King>
<Bishop>
<Soldier/>
</Bishop>
</King>
<Queen>
<Tower/>
</Queen>
</ChessBoard>
来自 Excel 工作簿,其中每个元素都包含一张幻灯片,第一列是其子元素的列表。如果(何时)解释不清楚,则链接到示例 Excel 工作簿:):https: //www.yousendit.com/download/TEhYc0x3NDQrV3h1a3NUQw
我事先不知道用户将制作多少张纸或元素/子项的数量,因此解析需要是动态的。
如果有人能指出我正确的方向,那将不胜感激。如果需要,如果有人想将其用作起点,我可以提供到目前为止的(非工作)代码。
提前致谢!
编辑——到目前为止的代码
Excel.Application xlApp;
xlApp = new Excel.Application();
Excel.Workbook xlWorkBook = null;
Excel.Worksheet xlWorkSheet;
Excel.Range range;
try
{
string str = string.Empty;
xlWorkBook = xlApp.Workbooks.Open(Excel_location + @"\Tree.xls",
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing);
using (XmlTextWriter writer = new XmlTextWriter(@"Tree.xml", Encoding.UTF8))
{
int rCnt = 0;// rCnt = row count
writer.WriteStartDocument();
Excel.Sheets sheets = xlWorkBook.Worksheets;
Excel.Range sheetrange = xlWorkSheet.UsedRange;
List<Excel.Worksheet> Sheets = new List<Excel.Worksheet>();
foreach (Excel.Worksheet s in xlWorkBook.Worksheets)
{
Sheets.Add(s);
}
bool first = true;
foreach (Excel.Worksheet s in Sheets)
{
if (first)
{
first = false;
sheetrange = s.UsedRange;
writer.WriteStartElement(s.Name);
for (rCnt = 1; rCnt <= sheetrange.Rows.Count; rCnt++)
{
string root = (string)(sheetrange.Cells[rCnt, 1] as Excel.Range).Value2.ToString();
writer.WriteStartElement(root);
foreach (Excel.Worksheet childsheet in Sheets)
{
if (childsheet.Name == root)
{
Excel.Range childsheetrange = childsheet.UsedRange;
for (int crCnt = 1; crCnt <= childsheetrange.Rows.Count; crCnt++)
{
str = (string)(childsheetrange.Cells[crCnt, 1] as Excel.Range).Value2.ToString();
writer.WriteStartElement(str);
foreach (Excel.Worksheet child2sheet in Sheets)
{
if (child2sheet.Name == str)
{
Excel.Range child2sheetrange = child2sheet.UsedRange;
for (int ccrCnt = 1; ccrCnt <= child2sheetrange.Rows.Count; ccrCnt++)
{
string str2 = (string)(child2sheetrange.Cells[ccrCnt, 1] as Excel.Range).Value2.ToString();
writer.WriteStartElement(str2);
writer.WriteEndElement();
}
}
}
writer.WriteEndElement();
}
}
}
writer.WriteEndElement();
}
writer.WriteEndElement();
}
}
}
xlWorkBook.Close(false, Excel_location + @"\Tree.xls", null);
xlApp.Quit();
}
catch (Exception)
{
xlWorkBook.Close(false, Excel_location + @"\Tree.xls", null);
xlApp.Quit();
throw;
}
很明显,上面的代码提出了一个“小”问题;当有超过 2 个子项时,事情将无法正常工作:D 当然我可以添加 25 个 foreach 循环,但我想要一个更复杂的解决方案.. 那么,如何更改代码以便它可以使用任意数字子元素?