天天看點

Parser XML and insert into DB with C#

1. Right click ->  Add -> New folder to add a folder to store the orginal File, named : orginalFile

2. Right click ->  Add -> New item -> Class to add new class ,named XMLUtils.cs

3. class XMLUtils

{

public static List<file_com> readXML()

{

XmlDocument doc = new XmlDocument();   // 利用doucment 類來讀取xml

doc.Load(@"..\..\orginalFile\test.xml");

XmlElement root = null ; //初始化根節點

root = doc.DoucmentElement;

XmlNodeList  listNodes = null; // 初始化節點清單

List<file_com>  list = new List<file_com>(); // new 一個對象? 

listNodes =  root.SelectNodes("/aa/bb/cc");

   foreach(XmlNode node in listNodes){

file_cmo cmo = new file_cmo();   // 建立一個對象

        cmo.ins_id = node.Attributes["id"].value;

com.in = getData("/aa/bb/cc/dd");

}

}

pubic static string Replace(String str){

if (str.contains("'"))

{ str = str.Replace("'","''");

}

return str;

}

public static string getData(XmlNode node, xpath){

string str = node.SelectSingleNode(xpath) == null? null : node.SelectSingleNode(xpath).InnerText;

if (str!=null){

 str = Replace(str);

}

return str;

}

}

4. DBUtils.cs

class DBUtils

{

private static SqlConnection GetEditorConnection()

{

return new SqlConnection(AppConfig.GetRequiredSetting("ExtClientConnStr"));  //

private static SqlConnection GetClientConnection()

        {

            return new SqlConnection(AppConfig.GetRequiredSetting("ExtEditorConnStr"));

        }

public static void saveToDB(List<file_cmo> list)

{

string sql = "";

string values = "";

int index = 1; 

foreach(file_cmo in list){

if (index % 10==1){

sql = "insert into TestFileData"(.....) values";

}else{

     values = values +",";

}

values = values +"('" + file_cmo.aa + "',"........+"')";

if (index%10==0||index ==list.Count)

{sql =sql+values;

setDataToTable(sql);

value = "";

sql = "";

}

index++;

}

}

public static vaoid setDataToTable(string sql)

SqlConnection conn = GetEditorConnection();

conn.Open();

SqlCommand cmd = new SqlCommand(sql,conn);

cmd.ExecuteNonQuery();

conn.close()

}

5. Program.cs

class Program

{

      DBUtils.saveToDB(XMLUtils.readXML())

}

App.config

<configuration>

  <appSettings>

    <add key="ExtClientConnStr" value="Data Source=.....;Initial Catalog=....;Integrated Security=SSPI;Application Name=.....;"/>

    <add key="ExtEditorConnStr" value="Data Source=.....;Initial Catalog=....;Integrated Security=SSPI;Application Name=.......;"/>   

  </appSettings>

    <startup> 

        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />

    </startup>

</configuration>