读XML的速度没有读数据库快
下面的是discuz中的的方法,你看看行不行
public abstract class XMLComponent
{
//源数据表
private DataTable sourceDT = null;
public DataTable SourceDataTable
{
set{sourceDT = value;}
get{return sourceDT;}
}
//文件输出路径
private string fileOutputPath = @"";
public string FileOutPath
{
set
{ //保证路径字符串变量的合法性
if (valueLastIndexOf("\\") != (valueLength-1))
fileOutputPath = value + "\\";
}
get{return fileOutputPath;}
}
//文件编码
private string fileEncode = "utf-8";
public string FileEncode
{
set{fileEncode = value;}
get{return fileEncode;}
}
//文件缩进
private int indentation = 6;
public int Indentation
{
set{indentation = value;}
get{return indentation;}
}
//文件缩进
private string version = "20";
public string Version
{
set{version = value;}
get{return version;}
}
//开始元素
private string startElement = "channel";
public string StartElement
{
set{startElement = value;}
get{return startElement;}
}
//XSL链接
private string xslLink = null;
public string XslLink
{
set{xslLink = value;}
get{return xslLink;}
}
//文件名
private string fileName = "MyFilexml";
public string FileName
{
set{fileName = value;}
get{return fileName;}
}
//表中指向父记录的字段名称
private string parentField = "Item";
public string ParentField
{
set{parentField = value;}
get{return parentField;}
}
//表中一个主键的值
private string key = "ItemID";
public string Key
{
set{key = value;}
get{return key;}
}
//写入文件
public abstract string WriteFile();
//写入StringBuilder对象
public abstract StringBuilder WriteStringBuilder();
public XmlDocument xmlDoc_Metone = new XmlDocument();
#region 构XML树
protected void BulidXmlTree(XmlElement tempXmlElement,string location)
{
DataRow tempRow = thisSourceDataTableSelect(thisKey + "=" + location)[0];
//生成Tree节点
XmlElement treeElement = xmlDoc_MetoneCreateElement(thisParentField);
tempXmlElementAppendChild(treeElement);
foreach(DataColumn c in thisSourceDataTableColumns) //依次找出当前记录的所有列属性
{
if ((cCaptionToString()ToLower() != thisParentFieldToLower()))
thisAppendChildElement(cCaptionToString()Trim()ToLower(),tempRow[cCaptionTrim()]ToString()Trim(),treeElement);
}
foreach (DataRow dr in thisSourceDataTableSelect(thisParentField + "=" + location))
{
if(thisSourceDataTableSelect("item=" + dr[thisKey]ToString())Length >= 0)
{
thisBulidXmlTree(treeElement,dr[thisKey]ToString()Trim());
}
else continue;
}
}
#endregion
#region 追加子节点
/// <summary>
/// 追加子节点
/// </summary>
/// <param name="strName">节点名字</param>
/// <param name="strInnerText">节点内容</param>
/// <param name="parentElement">父节点</param>
/// <param name="xmlDocument">XmlDocument对象</param>
protected void AppendChildElement(string strName , string strInnerText , XmlElement parentElement, XmlDocument xmlDocument )
{
XmlElement xmlElement = xmlDocumentCreateElement(strName) ;
xmlElementInnerText = strInnerText ;
parentElementAppendChild(xmlElement);
}
/// <summary>
/// 使用默认的频道Xml文档
/// </summary>
/// <param name="strName"></param>
/// <param name="strInnerText"></param>
/// <param name="parentElement"></param>
protected void AppendChildElement(string strName , string strInnerText , XmlElement parentElement )
{
AppendChildElement(strName,strInnerText,parentElement,xmlDoc_Metone);
}
#endregion
#region 创建存储生成XML的文件夹
public void CreatePath()
{
if (thisFileOutPath != null)
{
string path = thisFileOutPath; //;ServerMapPath("");
if (!DirectoryExists(path))
{
UtilsCreateDir(path);
}
}
else
{
string path = @"C:\"; //;ServerMapPath("");
string NowString = DateTimeNowToString("yyyy-M")Trim();
if (!DirectoryExists(path + NowString))
{
UtilsCreateDir(path + "\\" + NowString);
}
}
}
#endregion
}
//无递归直接生成XML
class ConcreteComponent : XMLComponent
{
private string strName;
public ConcreteComponent(string s)
{
strName = s;
}
//写入StringBuilder对象
public override StringBuilder WriteStringBuilder()
{
//string xmlData = stringFormat("<xml version='10' encoding='{0}'><xml-stylesheet type=\"text/xsl\" href=\"{1}\"><{3} version='{2}'></{3}>",thisFileEncode,thisXslLink,thisVersion,thisSourceDataTableTableName);
string xmlData = stringFormat("<xml version='10' encoding='{0}'><{3} ></{3}>",thisFileEncode,thisXslLink,thisVersion,thisSourceDataTableTableName);
thisxmlDoc_MetoneLoad(new StringReader(xmlData));
//写入channel
foreach(DataRow r in thisSourceDataTableRows) //依次取出所有行
{
//普通方式生成XML
XmlElement treeContentElement = thisxmlDoc_MetoneCreateElement(thisStartElement);
xmlDoc_MetoneDocumentElementAppendChild(treeContentElement);
foreach(DataColumn c in thisSourceDataTableColumns) //依次找出当前记录的所有列属性
{
thisAppendChildElement(cCaptionToString()ToLower(),r[c]ToString()Trim(),treeContentElement);
}
}
return new StringBuilder()Append(xmlDoc_MetoneInnerXml);
}
public override string WriteFile()
{
if (thisSourceDataTable != null)
{
DateTime filenamedate = DateTimeNow;
string filename = thisFileOutPath + thisFileName;
XmlTextWriter PicXmlWriter = null;
Encoding encode = EncodingGetEncoding(thisFileEncode);
CreatePath();
PicXmlWriter = new XmlTextWriter (filename,encode);
try
{
PicXmlWriterFormatting = FormattingIndented;
PicXmlWriterIndentation = thisIndentation;
PicXmlWriterNamespaces = false;
PicXmlWriterWriteStartDocument();
//PicXmlWriterWriteDocType("文档类型", null, "xml", null);
//PicXmlWriterWriteComment("按在数据库中记录的ID进行记录读写");
PicXmlWriterWriteProcessingInstruction("xml-stylesheet","type='text/xsl' href='" + thisXslLink + "'") ;
PicXmlWriterWriteStartElement(thisSourceDataTableTableName);
PicXmlWriterWriteAttributeString("", "version", null, thisVersion);
//写入channel
foreach(DataRow r in thisSourceDataTableRows) //依次取出所有行
{
PicXmlWriterWriteStartElement("",thisStartElement,"");
foreach(DataColumn c in thisSourceDataTableColumns) //依次找出当前记录的所有列属性
{
PicXmlWriterWriteStartElement("",cCaptionToString()Trim()ToLower(),"");
PicXmlWriterWriteString(r[c]ToString()Trim());
PicXmlWriterWriteEndElement();
}
PicXmlWriterWriteEndElement();
}
PicXmlWriterWriteEndElement();
PicXmlWriterFlush();
thisSourceDataTableDispose();
}
catch (Exception e) { ConsoleWriteLine ("异常:{0}", eToString()); }
finally
{
ConsoleWriteLine("对文件 {0} 的处理已完成。");
if (PicXmlWriter != null)
PicXmlWriterClose();
}
return filename;
}
else
{
ConsoleWriteLine("对文件 {0} 的处理未完成。");
return "";
}
}
}
//无递归直接生成XML
public class TreeNodeComponent : XMLComponent
{
private string strName;
public TreeNodeComponent(string s)
{
strName = s;
}
//写入StringBuilder对象
public override StringBuilder WriteStringBuilder()
{
//string xmlData = stringFormat("<xml version='10' encoding='{0}'><xml-stylesheet type=\"text/xsl\" href=\"{1}\"><{3} version='{2}'></{3}>",thisFileEncode,thisXslLink,thisVersion,thisSourceDataTableTableName);
string xmlData = stringFormat("<xml version='10' encoding='{0}'><{3} ></{3}>",thisFileEncode,thisXslLink,thisVersion,thisSourceDataTableTableName);
thisxmlDoc_MetoneLoad(new StringReader(xmlData));
//写入channel
foreach(DataRow r in thisSourceDataTableRows) //依次取出所有行
{
//普通方式生成XML
XmlElement treeContentElement = thisxmlDoc_MetoneCreateElement(thisStartElement);
xmlDoc_MetoneDocumentElementAppendChild(treeContentElement);
foreach(DataColumn c in thisSourceDataTableColumns) //依次找出当前记录的所有列属性
{
thisAppendChildElement(cCaptionToString()ToLower(),r[c]ToString()Trim(),treeContentElement);
}
}
return new StringBuilder()Append(xmlDoc_MetoneInnerXml);
}
public override string WriteFile()
{
if (thisSourceDataTable != null)
{
DateTime filenamedate = DateTimeNow;
string filename = thisFileOutPath + thisFileName;
XmlTextWriter PicXmlWriter = null;
Encoding encode = EncodingGetEncoding(thisFileEncode);
CreatePath();
PicXmlWriter = new XmlTextWriter (filename,encode);
try
{
PicXmlWriterFormatting = FormattingIndented;
PicXmlWriterIndentation = thisIndentation;
PicXmlWriterNamespaces = false;
PicXmlWriterWriteStartDocument();
//PicXmlWriterWriteDocType("文档类型", null, "xml", null);
//PicXmlWriterWriteComment("按在数据库中记录的ID进行记录读写");
PicXmlWriterWriteStartElement(thisSourceDataTableTableName);
string content = null;
//写入channel
foreach(DataRow r in thisSourceDataTableRows) //依次取出所有行
{
content = " Text=\"" + r[0]ToString()Trim() + "\" ImageUrl=\"//editor/images/smilies/" + r[1]ToString()Trim() + "\"";
PicXmlWriterWriteStartElement("",thisStartElement+content,"");
PicXmlWriterWriteEndElement();
content = null;
}
PicXmlWriterWriteEndElement();
PicXmlWriterFlush();
thisSourceDataTableDispose();
}
catch (Exception e)
{
ConsoleWriteLine ("异常:{0}", eToString());
}
finally
{
ConsoleWriteLine("对文件 {0} 的处理已完成。");
if (PicXmlWriter != null)
PicXmlWriterClose();
}
return filename;
}
else
{
ConsoleWriteLine("对文件 {0} 的处理未完成。");
return "";
}
}
}
//RSS生成
public class RssXMLComponent : XMLComponent
{
private string strName;
public RssXMLComponent(string s)
{
strName = s;
FileEncode ="gb2312";
Version = "20";
StartElement = "channel";
}
//写入StringBuilder对象
public override StringBuilder WriteStringBuilder()
{
string xmlData = stringFormat("<xml version='10' encoding='{0}'><xml-stylesheet type=\"text/xsl\" href=\"{1}\"><rss version='{2}'></rss>",thisFileEncode,thisXslLink,thisVersion);
thisxmlDoc_MetoneLoad(new StringReader(xmlData));
string Key = "-1";
//写入channel
foreach(DataRow r in thisSourceDataTableRows) //依次取出所有行
{
if ((thisKey != null) && (thisParentField != null)) //递归进行XML生成
{
if ((r[thisParentField]ToString()Trim() == "")||(r[thisParentField]ToString()Trim() == "0"))
{
XmlElement treeContentElement = thisxmlDoc_MetoneCreateElement(thisStartElement);
xmlDoc_MetoneDocumentElementAppendChild(treeContentElement);
foreach(DataColumn c in thisSourceDataTableColumns) //依次找出当前记录的所有列属性
{
if ((cCaptionToString()ToLower() == thisParentFieldToLower()))
{
Key = r[thisKey]ToString()Trim();
}
else
{
if ((r[thisParentField]ToString()Trim() == "")||(r[thisParentField]ToString()Trim() == "0"))
{
thisAppendChildElement(cCaptionToString()ToLower(),r[c]ToString()Trim(),treeContentElement);
}
}
}
foreach(DataRow dr in thisSourceDataTableSelect(thisParentField + "=" + Key))
{
if(thisSourceDataTableSelect(thisParentField + "=" + dr[thisKey]ToString())Length >= 0)
thisBulidXmlTree(treeContentElement,dr["ItemID"]ToString()Trim());
else
continue;
}
}
}
else //普通方式生成XML
{
XmlElement treeContentElement = thisxmlDoc_MetoneCreateElement(thisStartElement);
xmlDoc_MetoneDocumentElementAppendChild(treeContentElement);
foreach(DataColumn c in thisSourceDataTableColumns) //依次找出当前记录的所有列属性
{
thisAppendChildElement(cCaptionToString()ToLower(),r[c]ToString()Trim(),treeContentElement);
}
}
}
return new StringBuilder()Append(xmlDoc_MetoneInnerXml);
}
public override string WriteFile()
{
CreatePath();
string xmlData = stringFormat("<xml version='10' encoding='{0}'><xml-stylesheet type=\"text/xsl\" href=\"{1}\"><rss version='{2}'></rss>",thisFileEncode,thisXslLink,thisVersion);
thisxmlDoc_MetoneLoad(new StringReader(xmlData));
string Key = "-1";
//写入channel
foreach(DataRow r in thisSourceDataTableRows) //依次取出所有行
{
if ((thisKey != null)&&(thisParentField != null)) //递归进行XML生成
{
if ((r[thisParentField]ToString()Trim() == "")||(r[thisParentField]ToString()Trim() == "0"))
{
XmlElement treeContentElement = thisxmlDoc_MetoneCreateElement(thisStartElement);
xmlDoc_MetoneDocumentElementAppendChild(treeContentElement);
foreach(DataColumn c in thisSourceDataTableColumns) //依次找出当前记录的所有列属性
{
if ((cCaptionToString()ToLower() == thisParentFieldToLower()))
Key = r[thisKey]ToString()Trim();
else
{
if ((r[thisParentField]ToString()Trim() == "")||(r[thisParentField]ToString()Trim() == "0"))
{
thisAppendChildElement(cCaptionToString()ToLower(),r[c]ToString()Trim(),treeContentElement);
}
}
}
foreach(DataRow dr in thisSourceDataTableSelect(thisParentField + "=" + Key))
{
if(thisSourceDataTableSelect(thisParentField + "=" + dr[thisKey]ToString())Length >= 0)
thisBulidXmlTree(treeContentElement,dr["ItemID"]ToString()Trim());
else
continue;
}
}
}
else //普通方式生成XML
{
XmlElement treeContentElement = thisxmlDoc_MetoneCreateElement(thisStartElement);
xmlDoc_MetoneDocumentElementAppendChild(treeContentElement);
foreach(DataColumn c in thisSourceDataTableColumns) //依次找出当前记录的所有列属性
{
thisAppendChildElement(cCaptionToString()ToLower(),r[c]ToString()Trim(),treeContentElement);
}
}
}
string fileName = thisFileOutPath+thisFileName;
xmlDoc_MetoneSave(fileName);
return fileName;
}
}
//装饰器类
public class XMLDecorator : XMLComponent
{
protected XMLComponent ActualXMLComponent;
private string strDecoratorName;
public XMLDecorator (string str)
{
// how decoration occurs is localized inside this decorator
// For this demo, we simply print a decorator name
strDecoratorName = str;
}
public void SetXMLComponent(XMLComponent xc)
{
ActualXMLComponent = xc;
//ConsoleWriteLine("FileEncode - {0}", xcFileEncode);
GetSettingFromComponent( xc);
}
//将被装入的对象的默认设置为当前装饰者的初始值
public void GetSettingFromComponent(XMLComponent xc)
{
thisFileEncode = xcFileEncode;
thisFileOutPath = xcFileOutPath;
thisIndentation = xcIndentation;
thisSourceDataTable = xcSourceDataTable;
thisStartElement = xcStartElement;
thisVersion = xcVersion;
thisXslLink = xcXslLink;
thisKey = xcKey;
thisParentField = xcParentField;
}
public override string WriteFile()
{
if (ActualXMLComponent != null)
ActualXMLComponentWriteFile();
return null;
}
//写入StringBuilder对象
public override StringBuilder WriteStringBuilder()
{
if (ActualXMLComponent != null)
return ActualXMLComponentWriteStringBuilder();
return null;
}
}
SqlConnection con = new SqlConnection(Str);//连接数据库
下面这句改下就可以了:
string strSqls =stringFormat("select count(distinct customerid) as num from as_record where colldt>'{0}' and colldt<'{1}'",ds,de);
我刚碰到这个问题,是因为数据库的datetime类型默认值是0001-00-00,而sqldatetime的值必须介于 1/1/1753 12:00:00 AM 和 12/31/9999 11:59:59 PM 之间,所以就溢出了。
处理办法有很多:
(1)修改hbmxml文件中的类型,该"DateTime"为"String",该实体文件中的属性类型"DateTime"为"String"。
处理的时候,该属性值要么为空,要么是具有正确日期格式的字符串。
该方法只适合DateTime类型,而对int,bool类型就不适应了。下面就看第二种方法。
(2)Nullables处理
(1)添加引用:Nullablesdll与NullablesNHibernatedll
(2)修改配置文件hbmxml对应的类型,如:
<property name="InDate" column="inDate" type="DateTime"/>修改为:
<property name="InDate" column="inDate" type="NullablesNHibernateNullableDateTimeType,NullablesNHibernate"/>
(3)修改实体类文件,如:
private DateTime _inDate;
/// <summary>
/// 添加日期
/// </summary>
public DateTime InDate
{
get { return _inDate; }
set { _inDate = value;
} 修改为:
private NullablesNullableDateTime _InDate;
/// <summary>
/// 添加日期
/// </summary>
[NHibernateMappingAttributesProperty]
public NullablesNullableDateTime InDate
{
get { return _InDate; }
set { _InDate = value; }
}
(4)给属性InDate赋值:
Item clsItem = new Item();
clsItemInDate = new NullableDateTime(SystemDateTimeNow);
如果要输入空值,如:clsItemInDate = nulll;
(5)获取属性InDate的值:
ItemCRUD clsCRUD = new ItemCRUD(); //对实体类的 *** 作
Item clsItem = clsCRUDItemDetails(id); //获取实体类
thistxtInDateText = clsItemInDateToString();
有一些都没有试验过,按道理应该是都可以实现的,你选择一个适合自己的办法试试吧!我刚刚从java转做net有空可以多交流。
以上就是关于如何从数据库表中生成xml文件全部的内容,包括:如何从数据库表中生成xml文件、c#读出一个xml文档的两个时间字段,进入数据库查询,然后把值赋给lable,报从字符串转换为 datetime 时发、在使用NHibernate进行保存的时候,Session.Flush()的时间出现了SalDataTime溢出, 望高手指教,谢谢了等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)