简体   繁体   English

使用xmlreader将create xml文件更改为:Load to datatable

[英]Change create xml file to : Load to datatable, using xmlreader

I am using C# to create a Xml file on a drive and then write the contents of this file to a table. 我正在使用C#在驱动器上创建Xml file ,然后将该文件的内容写入表中。 But now I want to read the Xml string and write to a table without having to create the file and then write the contents of the file to a table. 但是现在我想读取Xml string并写入表中,而不必创建文件,然后将文件内容写入表中。

XmlDocument xdoc = new XmlDocument();
string fullFilePath = path + @"\Product.xml";
string Products;

Products = getProducts();
xdoc.LoadXml(Products);
xdoc.Save(String.Format(fullFilePath));

string connetionString = null;
SqlConnection connection;
SqlCommand command ;
SqlDataAdapter adpter = new SqlDataAdapter();
DataSet ds = new DataSet();
XmlReader xmlFile ;
string sql = null;

int product_ID = 0;
string Product_Name = null;
double product_Price = 0;

connetionString = "Data Source=servername;Initial Catalog=databasename;User ID=username;Password=password";

connection = new SqlConnection(connetionString);

xmlFile = XmlReader.Create("Product.xml", new XmlReaderSettings());
ds.ReadXml(xmlFile);
int i = 0;
connection.Open();
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
    product_ID = Convert.ToInt32(ds.Tables[0].Rows[i].ItemArray[0]);
    Product_Name = ds.Tables[0].Rows[i].ItemArray[1].ToString();
    product_Price = Convert.ToDouble(ds.Tables[0].Rows[i].ItemArray[2]);
    sql = "insert into Product values(" + product_ID + ",'" + Product_Name + "'," + product_Price + ")";
    command = new SqlCommand(sql, connection);
    adpter.InsertCommand = command;
    adpter.InsertCommand.ExecuteNonQuery();
}
connection.Close();

Unable to read the Xml string inline to write into the table. 无法读取内联的Xml string以写入表。

使用XmlDocument.Save()将其保存到内存流中,然后使用DataSet.ReadXml()从该内存流中读取它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM