/// <summary> /// 根据节点信息构造表格的头部,并返回数据绑定列 /// </summary> /// <param name="rootNode"></param> /// <param name="IsTrue"></param> /// <param name="condition"></param> /// <param name="dataColumns"></param> /// <returns></returns> public static string BuildTableHead(ColumnNode rootNode, IsTrueHandler IsTrue, NodeCondition condition, out List <ColumnNode> dataColumns) { //遍历模板树,构造一棵符合条件的树,用于生成表 TraversalTree(rootNode, IsTrue, condition); //根据树得到头部列表 List <List <ColumnNode> > headRows = new List <List <ColumnNode> >(); dataColumns = new List <ColumnNode>(); ConvertTreeToList(rootNode, headRows, dataColumns); StringBuilder htmlBuilder = new StringBuilder(); htmlBuilder.Append("<thead>"); for (int i = 1; i < headRows.Count; i++) { htmlBuilder.Append("<tr style=\"text-align:center;\">"); for (int j = 0; j < headRows[i].Count; j++) { //如果没有子节点,行数=总行数-当前的层级 int rowSpan = headRows[i][j].Children.Count == 0 ? headRows.Count - headRows[i][j].Level : 1; htmlBuilder.AppendFormat("<th colspan=\"{0}\" rowspan=\"{1}\">{2}</th>", headRows[i][j].ColSpan, rowSpan, headRows[i][j].Title); } htmlBuilder.Append("</tr>"); } htmlBuilder.Append("</thead>"); return(htmlBuilder.ToString()); }
/// <summary> /// 遍历树 /// </summary> /// <param name="rootNode"></param> /// <param name="IsTrue"></param> /// <param name="condition"></param> public static void TraversalTree(ColumnNode rootNode, IsTrueHandler IsTrue, NodeCondition condition) { rootNode.Children = new List <object>(); foreach (XmlNode node in rootNode.CorrespondXmlNode.ChildNodes) { if (IsTrue(condition, node)) { rootNode.Children.Add( new ColumnNode { CorrespondXmlNode = node, Title = node.Attributes["title"].Value, Name = node.Attributes["name"].Value, Level = rootNode.Level + 1 }); } } foreach (object node in rootNode.Children) { TraversalTree((ColumnNode)node, IsTrue, condition); } //如果只有一个子节点,则去除该节点,去除节点的子节点上移 if (rootNode.Children.Count == 1) { rootNode.Children = ((ColumnNode)rootNode.Children[0]).Children; foreach (object node in rootNode.Children) { ((ColumnNode)node).Level = rootNode.Level + 1; TraversalTree((ColumnNode)node, IsTrue, condition); } } foreach (object node in rootNode.Children) { rootNode.ColSpan += ((ColumnNode)node).ColSpan; } rootNode.ColSpan = rootNode.ColSpan == 0 ? 1 : rootNode.ColSpan; }