原文: 将RDL報表轉換成RDLC報表的函數
近日研究RDLC報表,發現其不能與RDL報表相容,尤其是将RDL報表轉換成RDLC報表。網上的資料貼出的的轉換方式複雜且不切實際,遂決定深入研究。經研究發現,RDL報表與RDLC報表的XML格式有些差異,将RDL報表的XML格式改成與RDLC報表的XML格式相同,發現轉換成功! 如需轉換123.rdl檔案,隻需RDLConvertRDLC("123.rdl"),即可轉換成123.rdlc檔案。由于本人對帶命名空間的XML檔案操作不熟悉,不能将除根節點意外的其他節點的xmlns屬性隻去掉,如有高手,歡迎指教!
private void RDLConvertRDLC(string strFile)
{
if(File.Exists(strFile))
{
try
{
XmlDocument xmlBak;
XmlNamespaceManager nsMgrBak;
XmlNodeList Reports;
// 打開需轉換的XML檔案
try
{
xmlBak = new XmlDocument();
xmlBak.Load(strFile);
nsMgrBak = new XmlNamespaceManager(xmlBak.NameTable);
nsMgrBak.AddNamespace("nsBak", "http://schemas.microsoft.com/sqlserver/reporting/2010/01/reportdefinition");
Reports = xmlBak.SelectSingleNode("/nsBak:Report", nsMgrBak).ChildNodes;
}
catch
{
File.Move(strFile, strFile + "c");
return;
}
// 建立新的XML檔案
XmlDocument xmlDoc = new XmlDocument();
XmlDeclaration dec = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null);
xmlDoc.AppendChild(dec);
// 建立一個根節點Report
XmlElement root = xmlDoc.CreateElement("Report");
root.SetAttribute("xmlns:rd", "http://schemas.microsoft.com/SQLServer/reporting/reportdesigner");
root.SetAttribute("xmlns", "http://schemas.microsoft.com/sqlserver/reporting/2008/01/reportdefinition");
xmlDoc.AppendChild(root);
// 拷貝節點資料到新XML檔案
for (int i = 0; i < Reports.Count; i++)
{
if (Reports[i].Name != "AutoRefresh")
{
if (Reports[i].Name == "ReportSections")
{
XmlNodeList ReportSections = xmlBak.SelectSingleNode("/nsBak:Report/nsBak:ReportSections/nsBak:ReportSection", nsMgrBak).ChildNodes;
for (int j = 0; j < ReportSections.Count; j++)
{
XmlElement newElement = (XmlElement)xmlDoc.ImportNode(ReportSections[j], true);
newElement.SetAttribute("xmlns", "http://schemas.microsoft.com/sqlserver/reporting/2008/01/reportdefinition");
root.AppendChild(newElement);
}
}
else
{
XmlElement newElement = (XmlElement)xmlDoc.ImportNode(Reports[i], true);
newElement.SetAttribute("xmlns", "http://schemas.microsoft.com/sqlserver/reporting/2008/01/reportdefinition");
root.AppendChild(newElement);
}
}
}
xmlDoc.Save(@strFile + "c");
File.Delete(strFile);
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message.ToString(), "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
else
{
MessageBox.Show("檔案"+strFile+"不存在!", "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}