using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.Xsl;
using System.Data;
using System.Windows.Forms;
namespace Demo
{
class XMLManger
{
//加载数据
public void addInfo(DataTable dt)
{
SaveFileDialog sfdXML = new SaveFileDialog();
sfdXML.Filter = "XML文件(*.xml)|*.xml";
sfdXML.ShowDialog();
string xmlPath = sfdXML.FileName;
if (xmlPath.Length > 0)
{
//XML文件
writeXML(xmlPath,dt);
MessageBox.Show("XML文件加载数据成功!");
}
}
//将数据写入到XML文档
private void writeXML(string path,DataTable dt)
{
XmlWriter myWrite = XmlWriter.Create(path);
myWrite.WriteStartDocument();
myWrite.WriteWhitespace("\n");
myWrite.WriteStartElement("titles");
foreach (DataRow dr in dt.Rows)
{
myWrite.WriteStartElement("titleDemo");
myWrite.WriteStartElement("title_id");
myWrite.WriteString(dr[0].ToString());
myWrite.WriteEndElement();
myWrite.WriteStartElement("title");
myWrite.WriteString(dr[1].ToString());
myWrite.WriteEndElement();
myWrite.WriteStartElement("type");
myWrite.WriteString(dr[2].ToString());
myWrite.WriteEndElement();
myWrite.WriteStartElement("pub_id");
myWrite.WriteString(dr[3].ToString());
myWrite.WriteEndElement();
myWrite.WriteStartElement("price");
myWrite.WriteString(dr[4].ToString());
myWrite.WriteEndElement();
myWrite.WriteStartElement("advance");
myWrite.WriteString(dr[5].ToString());
myWrite.WriteEndElement();
myWrite.WriteStartElement("royalty");
myWrite.WriteString(dr[6].ToString());
myWrite.WriteEndElement();
myWrite.WriteStartElement("ytd_sales");
myWrite.WriteString(dr[7].ToString());
myWrite.WriteEndElement();
myWrite.WriteEndElement();
}
myWrite.WriteEndElement();
myWrite.Close();
}
//XML文件转化为HTML文件
public void tranInfo(string xslpath,string xmlPath)
{
XslCompiledTransform xslTran = new XslCompiledTransform();
//加载指定的XSL文件
xslTran.Load(xslpath);
//转化 生成网页
//指定网页的位置
SaveFileDialog sfdXML = new SaveFileDialog();
sfdXML.Filter = "HTML文件(*.html)|*.html";
sfdXML.ShowDialog();
string htmlPath = sfdXML.FileName;
if(htmlPath.Length>0)
{
xslTran.Transform(xmlPath, htmlPath);
MessageBox.Show("文件转换成功!");
}
}
}
}