读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 (value.LastIndexOf("\\") != (value.Length-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 = "2.0";
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 = "MyFile.xml";
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 = this.SourceDataTable.Select(this.Key + "=" + location)[0];
//生成Tree节点
XmlElement treeElement = xmlDoc_Metone.CreateElement(this.ParentField);
tempXmlElement.AppendChild(treeElement);
foreach(DataColumn c in this.SourceDataTable.Columns) //依次找出当前记录的所有列属性
{
if ((c.Caption.ToString().ToLower() != this.ParentField.ToLower()))
this.AppendChildElement(c.Caption.ToString().Trim().ToLower(),tempRow[c.Caption.Trim()].ToString().Trim(),treeElement);
}
foreach (DataRow dr in this.SourceDataTable.Select(this.ParentField + "=" + location))
{
if(this.SourceDataTable.Select("item=" + dr[this.Key].ToString()).Length >= 0)
{
this.BulidXmlTree(treeElement,dr[this.Key].ToString().Trim());
}
else continue;
}
}
#endregion
#region 追加子节点
///
/// 追加子节点
///
/// 节点名字
/// 节点内容
/// 父节点
/// XmlDocument对象
protected void AppendChildElement(string strName , string strInnerText , XmlElement parentElement, XmlDocument xmlDocument )
{
XmlElement xmlElement = xmlDocument.CreateElement(strName) ;
xmlElement.InnerText = strInnerText ;
parentElement.AppendChild(xmlElement);
}
///
/// 使用默认的频道Xml文档
///
///
///
///
protected void AppendChildElement(string strName , string strInnerText , XmlElement parentElement )
{
AppendChildElement(strName,strInnerText,parentElement,xmlDoc_Metone);
}
#endregion
#region 创建存储生成XML的文件夹
public void CreatePath()
{
if (this.FileOutPath != null)
{
string path = this.FileOutPath; //;Server.MapPath("");
if (!Directory.Exists(path))
{
Utils.CreateDir(path);
}
}
else
{
string path = @"C:\"; //;Server.MapPath("");
string NowString = DateTime.Now.ToString("yyyy-M").Trim();
if (!Directory.Exists(path + NowString))
{
Utils.CreateDir(path + "\\" + NowString);
}
}
}
#endregion
}
//无递归直接生成XML
class ConcreteComponent : XMLComponent
{
private string strName;
public ConcreteComponent(string s)
{
strName = s;
}
//写入StringBuilder对象
public override StringBuilder WriteStringBuilder()
{
//string xmlData = string.Format("<{3} version='{2}'>{3}>",this.FileEncode,this.XslLink,this.Version,this.SourceDataTable.TableName);
string xmlData = string.Format("<{3} >{3}>",this.FileEncode,this.XslLink,this.Version,this.SourceDataTable.TableName);
this.xmlDoc_Metone.Load(new StringReader(xmlData));
//写入channel
foreach(DataRow r in this.SourceDataTable.Rows) //依次取出所有行
{
//普通方式生成XML
XmlElement treeContentElement = this.xmlDoc_Metone.CreateElement(this.StartElement);
xmlDoc_Metone.DocumentElement.AppendChild(treeContentElement);
foreach(DataColumn c in this.SourceDataTable.Columns) //依次找出当前记录的所有列属性
{
this.AppendChildElement(c.Caption.ToString().ToLower(),r[c].ToString().Trim(),treeContentElement);
}
}
return new StringBuilder().Append(xmlDoc_Metone.InnerXml);
}
public override string WriteFile()
{
if (this.SourceDataTable != null)
{
DateTime filenamedate = DateTime.Now;
string filename = this.FileOutPath + this.FileName;
XmlTextWriter PicXmlWriter = null;
Encoding encode = Encoding.GetEncoding(this.FileEncode);
CreatePath();
PicXmlWriter = new XmlTextWriter (filename,encode);
try
{
PicXmlWriter.Formatting = Formatting.Indented;
PicXmlWriter.Indentation = this.Indentation;
PicXmlWriter.Namespaces = false;
PicXmlWriter.WriteStartDocument();
//PicXmlWriter.WriteDocType("文档类型", null, ".xml", null);
//PicXmlWriter.WriteComment("按在数据库中记录的ID进行记录读写");
PicXmlWriter.WriteProcessingInstruction("xml-stylesheet","type='text/xsl' href='" + this.XslLink + "'") ;
PicXmlWriter.WriteStartElement(this.SourceDataTable.TableName);
PicXmlWriter.WriteAttributeString("", "version", null, this.Version);
//写入channel
foreach(DataRow r in this.SourceDataTable.Rows) //依次取出所有行
{
PicXmlWriter.WriteStartElement("",this.StartElement,"");
foreach(DataColumn c in this.SourceDataTable.Columns) //依次找出当前记录的所有列属性
{
PicXmlWriter.WriteStartElement("",c.Caption.ToString().Trim().ToLower(),"");
PicXmlWriter.WriteString(r[c].ToString().Trim());
PicXmlWriter.WriteEndElement();
}
PicXmlWriter.WriteEndElement();
}
PicXmlWriter.WriteEndElement();
PicXmlWriter.Flush();
this.SourceDataTable.Dispose();
}
catch (Exception e) { Console.WriteLine ("异常:{0}", e.ToString()); }
finally
{
Console.WriteLine("对文件 {0} 的处理已完成。");
if (PicXmlWriter != null)
PicXmlWriter.Close();
}
return filename;
}
else
{
Console.WriteLine("对文件 {0} 的处理未完成。");
return "";
}
}
}
//无递归直接生成XML
public class TreeNodeComponent : XMLComponent
{
private string strName;
public TreeNodeComponent(string s)
{
strName = s;
}
//写入StringBuilder对象
public override StringBuilder WriteStringBuilder()
{
//string xmlData = string.Format("<{3} version='{2}'>{3}>",this.FileEncode,this.XslLink,this.Version,this.SourceDataTable.TableName);
string xmlData = string.Format("<{3} >{3}>",this.FileEncode,this.XslLink,this.Version,this.SourceDataTable.TableName);
this.xmlDoc_Metone.Load(new StringReader(xmlData));
//写入channel
foreach(DataRow r in this.SourceDataTable.Rows) //依次取出所有行
{
//普通方式生成XML
XmlElement treeContentElement = this.xmlDoc_Metone.CreateElement(this.StartElement);
xmlDoc_Metone.DocumentElement.AppendChild(treeContentElement);
foreach(DataColumn c in this.SourceDataTable.Columns) //依次找出当前记录的所有列属性
{
this.AppendChildElement(c.Caption.ToString().ToLower(),r[c].ToString().Trim(),treeContentElement);
}
}
return new StringBuilder().Append(xmlDoc_Metone.InnerXml);
}
public override string WriteFile()
{
if (this.SourceDataTable != null)
{
DateTime filenamedate = DateTime.Now;
string filename = this.FileOutPath + this.FileName;
XmlTextWriter PicXmlWriter = null;
Encoding encode = Encoding.GetEncoding(this.FileEncode);
CreatePath();
PicXmlWriter = new XmlTextWriter (filename,encode);
try
{
PicXmlWriter.Formatting = Formatting.Indented;
PicXmlWriter.Indentation = this.Indentation;
PicXmlWriter.Namespaces = false;
PicXmlWriter.WriteStartDocument();
//PicXmlWriter.WriteDocType("文档类型", null, ".xml", null);
//PicXmlWriter.WriteComment("按在数据库中记录的ID进行记录读写");
PicXmlWriter.WriteStartElement(this.SourceDataTable.TableName);
string content = null;
//写入channel
foreach(DataRow r in this.SourceDataTable.Rows) //依次取出所有行
{
content = " Text=\"" + r[0].ToString().Trim() + "\" ImageUrl=\"../../editor/images/smilies/" + r[1].ToString().Trim() + "\"";
PicXmlWriter.WriteStartElement("",this.StartElement+content,"");
PicXmlWriter.WriteEndElement();
content = null;
}
PicXmlWriter.WriteEndElement();
PicXmlWriter.Flush();
this.SourceDataTable.Dispose();
}
catch (Exception e)
{
Console.WriteLine ("异常:{0}", e.ToString());
}
finally
{
Console.WriteLine("对文件 {0} 的处理已完成。");
if (PicXmlWriter != null)
PicXmlWriter.Close();
}
return filename;
}
else
{
Console.WriteLine("对文件 {0} 的处理未完成。");
return "";
}
}
}
//RSS生成
public class RssXMLComponent : XMLComponent
{
private string strName;
public RssXMLComponent(string s)
{
strName = s;
FileEncode ="gb2312";
Version = "2.0";
StartElement = "channel";
}
//写入StringBuilder对象
public override StringBuilder WriteStringBuilder()
{
string xmlData = string.Format("
this.xmlDoc_Metone.Load(new StringReader(xmlData));
string Key = "-1";
//写入channel
foreach(DataRow r in this.SourceDataTable.Rows) //依次取出所有行
{
if ((this.Key != null) && (this.ParentField != null)) //递归进行XML生成
{
if ((r[this.ParentField].ToString().Trim() == "")||(r[this.ParentField].ToString().Trim() == "0"))
{
XmlElement treeContentElement = this.xmlDoc_Metone.CreateElement(this.StartElement);
xmlDoc_Metone.DocumentElement.AppendChild(treeContentElement);
foreach(DataColumn c in this.SourceDataTable.Columns) //依次找出当前记录的所有列属性
{
if ((c.Caption.ToString().ToLower() == this.ParentField.ToLower()))
{
Key = r[this.Key].ToString().Trim();
}
else
{
if ((r[this.ParentField].ToString().Trim() == "")||(r[this.ParentField].ToString().Trim() == "0"))
{
this.AppendChildElement(c.Caption.ToString().ToLower(),r[c].ToString().Trim(),treeContentElement);
}
}
}
foreach(DataRow dr in this.SourceDataTable.Select(this.ParentField + "=" + Key))
{
if(this.SourceDataTable.Select(this.ParentField + "=" + dr[this.Key].ToString()).Length >= 0)
this.BulidXmlTree(treeContentElement,dr["ItemID"].ToString().Trim());
else
continue;
}
}
}
else //普通方式生成XML
{
XmlElement treeContentElement = this.xmlDoc_Metone.CreateElement(this.StartElement);
xmlDoc_Metone.DocumentElement.AppendChild(treeContentElement);
foreach(DataColumn c in this.SourceDataTable.Columns) //依次找出当前记录的所有列属性
{
this.AppendChildElement(c.Caption.ToString().ToLower(),r[c].ToString().Trim(),treeContentElement);
}
}
}
return new StringBuilder().Append(xmlDoc_Metone.InnerXml);
}
public override string WriteFile()
{
CreatePath();
string xmlData = string.Format("
this.xmlDoc_Metone.Load(new StringReader(xmlData));
string Key = "-1";
//写入channel
foreach(DataRow r in this.SourceDataTable.Rows) //依次取出所有行
{
if ((this.Key != null)&&(this.ParentField != null)) //递归进行XML生成
{
if ((r[this.ParentField].ToString().Trim() == "")||(r[this.ParentField].ToString().Trim() == "0"))
{
XmlElement treeContentElement = this.xmlDoc_Metone.CreateElement(this.StartElement);
xmlDoc_Metone.DocumentElement.AppendChild(treeContentElement);
foreach(DataColumn c in this.SourceDataTable.Columns) //依次找出当前记录的所有列属性
{
if ((c.Caption.ToString().ToLower() == this.ParentField.ToLower()))
Key = r[this.Key].ToString().Trim();
else
{
if ((r[this.ParentField].ToString().Trim() == "")||(r[this.ParentField].ToString().Trim() == "0"))
{
this.AppendChildElement(c.Caption.ToString().ToLower(),r[c].ToString().Trim(),treeContentElement);
}
}
}
foreach(DataRow dr in this.SourceDataTable.Select(this.ParentField + "=" + Key))
{
if(this.SourceDataTable.Select(this.ParentField + "=" + dr[this.Key].ToString()).Length >= 0)
this.BulidXmlTree(treeContentElement,dr["ItemID"].ToString().Trim());
else
continue;
}
}
}
else //普通方式生成XML
{
XmlElement treeContentElement = this.xmlDoc_Metone.CreateElement(this.StartElement);
xmlDoc_Metone.DocumentElement.AppendChild(treeContentElement);
foreach(DataColumn c in this.SourceDataTable.Columns) //依次找出当前记录的所有列属性
{
this.AppendChildElement(c.Caption.ToString().ToLower(),r[c].ToString().Trim(),treeContentElement);
}
}
}
string fileName = this.FileOutPath+this.FileName;
xmlDoc_Metone.Save(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;
//Console.WriteLine("FileEncode - {0}", xc.FileEncode);
GetSettingFromComponent( xc);
}
//将被装入的对象的默认设置为当前装饰者的初始值
public void GetSettingFromComponent(XMLComponent xc)
{
this.FileEncode = xc.FileEncode;
this.FileOutPath = xc.FileOutPath;
this.Indentation = xc.Indentation;
this.SourceDataTable = xc.SourceDataTable;
this.StartElement = xc.StartElement;
this.Version = xc.Version;
this.XslLink = xc.XslLink;
this.Key = xc.Key;
this.ParentField = xc.ParentField;
}
public override string WriteFile()
{
if (ActualXMLComponent != null)
ActualXMLComponent.WriteFile();
return null;
}
//写入StringBuilder对象
public override StringBuilder WriteStringBuilder()
{
if (ActualXMLComponent != null)
return ActualXMLComponent.WriteStringBuilder();
return null;
}
}
对于楼主这个问题,如果还是多重节点的话会很麻烦.
首先从最基本的开始吧:
using System.Xml;
引入Xml命名空间,
然后建立一个XML文档.
XmlTextWriter writer = new XmlTextWriter("tree.xml", System.Text.Encoding.UTF8);
建立根节点:
writer.WriteStartDocument();
writer.WriteStartElement("tree");
writer.WriteEndElement();
writer.WriteEndDocument();
这样就建立了
接着开始读数据,首先提取节点字段为最高层的所有记录.并填充到数据集中,然后用循环
writer.WriteStartDocument();
writer.WriteStartElement("tree");
for(int r=0;r
//在这里面添加
writer.WriteStartElement(ds.Tables[0].Row[r][节点名称].ToString());
writer.WriteStartString(节点元素标签中间的文字);
writer.WriteEndElement();
}
writer.WriteEndElement();
writer.WriteEndDocument();
以上就可以写出第一层节点的内容了.
然后依次提取第二层的,注意是属于哪一个父节点的第二层,就添至哪个节点下.
添至某个节点下的新节点的方法
XmlDocument document = new XmlDocument();
document.Load("tree.xml");
XmlNodeList list= document.GetElementsByTagName(节点名称);
获得为此标签名的节点集合.
然后建立一个XmlNode对象,用list.AppendChildNode()方法增加这个子XmlNode.
这个子XmlNode就是子节点...
具体的方法暂时我也不太清楚了,不好意思.只能奉献这么多了...
这乱就乱在每个子节点都要去判断是第几层节点,父节点是谁,如果节点层次太深,弄个4,5层的还好,再搞个节点数量是动态添加的...
估计累死我也弄不出来了,不知道有没高人有更好的办法.
public class Board
{
private XmlDocument domNav = new XmlDocument();
private XmlNode root;
public Board()
{
domNav.LoadXml("
root = domNav.DocumentElement;
}
public string GetXMLString(int boardId)
{
if (boardId < 0)
boardId = 0;
SqlParameter[] prams = { DBAdapter.MakeInParam("@SubRootID", SqlDbType.Int, 4, boardId) };
DataSet ds = null;
DBAdapter.RunProc("F_GetBoardTree", prams, out ds);
foreach (DataRow myRow in ds.Tables[0].Rows)
{
AppendNode(myRow["ParentID"].ToString(), myRow["BoardID"].ToString(),
myRow["BoardName"].ToString(), myRow["Logo"].ToString());
}
return domNav.OuterXml;
}
void AppendNode(string parentId, string boardId, string boardName, string logo)
{
if (parentId == "0")
{
XmlElement newE = domNav.CreateElement(null, "Entity", null);
newE.InnerXml = "
+ "
+ "
newE.SetAttribute("id", null, "1");
domNav.DocumentElement.AppendChild(newE);
return;
}
else
{
XmlNode targNode = domNav.DocumentElement.SelectSingleNode("//*[@id=" + parentId + "]");
if (targNode != null)
{
targNode = targNode.ChildNodes[2];
XmlElement newE = domNav.CreateElement(null, "Entity", null);
newE.InnerXml = "
+ "
+ "
newE.SetAttribute("id", null, boardId);
targNode.AppendChild(newE);
return;
}
}
return;
}
}