更新时间:2023-11-24 20:57:10
试试这个..
这里的代码是flImport是我的文件上传器,plImport是我的面板和ckContent是我的CKEditor。此代码返回一个Html表。它将Xml文件转换为Html表格结构。
This is the code here flImport is my fileuploader and plImport is my panel and ckContent is my CKEditor. This Code Returns an Html Table . It converts Xml files to Html table Structure.
protected void btUpload_Click(object sender, EventArgs e)
{
string fullFilePath = null;
if (flImport.HasFile)
{
string fileName = string.Empty;
string extension = string.Empty;
string path = string.Empty;
fileName = flImport.PostedFile.FileName;
string flFilePath = Server.MapPath("~/Files/" + fileName);
flImport.SaveAs(Server.MapPath("~/Files/" + fileName));
fullFilePath = flFilePath;
extension = Path.GetExtension(fileName);
path = fileName;
if (string.Equals(extension, ".xml") || string.Equals(extension, ".xslt"))
{
string xml= System.IO.File.ReadAllText(fullFilePath);
ckContent.Text = ConvertXmlToHtmlTable(xml);
}
}
plImport.Visible = false;
}
protected string ConvertXmlToHtmlTable(string xml)
{
StringBuilder html = new StringBuilder("<table align="center" hold=" /> " border="1" class="xmlTable">\r\n");
try
{
XDocument xDocument = XDocument.Parse(xml);
XElement root = xDocument.Root;
var xmlAttributeCollection = root.Elements().Attributes();
foreach (var ele in root.Elements())
{
if (!ele.HasElements)
{
string elename = "";
html.Append("<tr>");
elename = ele.Name.ToString();
if (ele.HasAttributes)
{
IEnumerable<xattribute> attribs = ele.Attributes();
foreach (XAttribute attrib in attribs)
elename += Environment.NewLine + attrib.Name.ToString() +
"=" + attrib.Value.ToString();
}
html.Append("<table><tbody><tr><table><tbody><tr><td>" + elename + "</td></tr></tbody></table></tr></tbody></table>");
html.Append("<table><tbody><tr><td>" + ele.Value + "</td></tr></tbody></table>");
html.Append("</xattribute></tr>");
}
else
{
string elename = "";
html.Append("<tr>");
elename = ele.Name.ToString();
if (ele.HasAttributes)
{
IEnumerable<xattribute> attribs = ele.Attributes();
foreach (XAttribute attrib in attribs)
elename += Environment.NewLine + attrib.Name.ToString() + "=" + attrib.Value.ToString();
}
html.Append("<table><tbody><tr><table><tbody><tr><td>" + elename + "</td></tr></tbody></table></tr></tbody></table>");
html.Append("<table><tbody><tr><td>" + ConvertXmlToHtmlTable(ele.ToString()) + "</td></tr></tbody></table>");
html.Append("</xattribute></tr>");
}
}
html.Append("</table>");
}
catch (Exception e)
{
return xml;
// Returning the original string incase of error.
}
return html.ToString();
}
以上代码适用于我的项目。谢谢大家。
The above code works in my project. Thanks Everybody.