2005-10-3
A class that operates XML through DataSet
The projects I wrote during this period always use XML to save some configurations, and every time I operate XML, I feel it is quite troublesome and not as easy as the database. Later, I found that using DataSet to operate XML is very convenient and has better flexibility, so I wrote a class to operate XML to deal with general XML operations (source code download attachment).
1 Basic ideas
In fact, using DataSet to operate XML is ultimately about operating tables, rows, columns, etc. in DataSet, and then rewrite them into XML using the things in DataSet to achieve the purpose of editing XML. If combined with .xsd files, the effect will be better.
2 Program details
(1) XML file content
The XML of this class's operations and the generated XML format are the same, as follows:
/xml_xmlDB.xsd">
2 Programmers
2
Develop B/S structure program
c# etc.
Jianguo Road XXX
2008-8-31
false
4
C# programmer
2
Develop B/S structure program
c# etc.
Jianguo Road XXX
2008-8-31
false
Then click "Data" in the lower right corner of the XML file to see the familiar form. Right-click anywhere in the table to select "Create Schema", and a .xsd file will be generated, which is used to define the types of XML columns. The content is as follows (click to view the attachment of Code 2):
/xml_xmlDB.xsd" xmlns:mstns="/xml_xmlDB.xsd"xmlns="/xml_xmlDB.xsd" xmlns:xs="http:///2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"attributeFormDefault="qualified" elementFormDefault="qualified"> msdata:Locale="zh-CN" msdata:EnforceConstaints="False">?msdata:AutoIncrement="true" msdata:AutoIncrementStep="1"msdata:AutoIncrementSeed="1" />
Note: If you want to have an automatically growing ID field like a database, you can do this:
First add an element in the XML, so when generating .xsd, there will be an ID segment. Select the ID column in .xsd. In the property on the right, set "AutoIncrementSeed" and "AutoIncrementStep" to 1 respectively, so that the ID will automatically grow from 1 with a step size of 1.
It doesn't matter if we don't understand the above code, because we can generate content in this format through DataSet. Next, the XML operation will begin.
(2) Process XML file path
Here we mainly process the incoming XML path. If the incoming is a relative path, the full path will be returned. If the incoming is a complete path, it will be returned without processing. The method is as follows:
#region GetXmlFullPath
///
/// Return to the full path
///
/// The path to Xml
///
public static string GetXmlFullPath(string strPath)
{
//If the path contains a : symbol, it is considered that the incoming path is the complete path
if((":") > 0)
{
return strPath;
}
else
{
//Return to the full path
return (strPath);
}
}
#endregion
(3) Read records
The method to read XML data into DataSet is:
#region GetDataSetByXml
///
/// Read xml and return directly to DataSet
///
/// xml file relative path
///
public static DataSet GetDataSetByXml(string strXmlPath)
{
try
{
DataSet ds = new DataSet();
//Read XML to DataSet
(GetXmlFullPath(strXmlPath));
if( > 0)
{
return ds;
}
return null;
}
catch(Exception)
{
return null;
}
}
#endregion
The above method will obtain a DataSet, which stores all XML records and has not been processed. But many times we only need some records that meet the conditions, and we need to use the following methods to obtain:
#region GetDataViewByXml
/// 〈summary〉
/// Read Xml to return a sorted or filtered DataView
/// 〈/summary〉
/// 〈param name="strXmlPath"〉〈/param〉
/// 〈param name="strWhere"> filter conditions, such as: "name = 'kgdiwss'"〈/param>
/// 〈param name="strSort"> sorting conditions, such as: "Id desc"〈/param>
/// 〈returns〉〈/returns〉
public static DataView GetDataViewByXml(string strXmlPath,string strWhere,string strSort)
{
try
{
DataSet ds = new DataSet();
(GetXmlFullPath(strXmlPath));
//Create DataView to complete sorting or filtering operations
DataView dv = new DataView([0]);
if(strSort != null)
{
//Sort the records in the DataView
= strSort;
}
if(strWhere != null)
{
//Filter the records in the DataView and find the records we want
= strWhere;
}
return dv;
}
catch(Exception)
{
return null;
}
}
#endregion
(4) Insert record
So far, we can read records in XML at will. Next, we will implement the operation of writing to XML. The method is as follows:
#region WriteXmlByDataSet
/// 〈summary〉
/// Insert a line of data into the Xml file
/// 〈/summary〉
/// 〈param name="strXmlPath"〉xml file relative path〈/param〉
/// 〈param name="Columns"〉Array of column names to be inserted in rows, such as: string[] Columns = {"name", "IsMarried"};〈/param〉
/// 〈param name="ColumnValue">Add to insert the value array of each column of the row, such as: string[] ColumnValue={"kgdiwss", "false"};〈/param>
/// 〈returns〉 returns true successfully, otherwise it returns false〈/returns〉
public static bool WriteXmlByDataSet(string strXmlPath,string[] Columns,string[] ColumnValue)
{
try
{
//Get the path of .XSD based on the incoming XML path, and the two files are placed in the same directory string strXsdPath = (0, (".")) + ".xsd";
DataSet ds = new DataSet();
//Read the xml schema, related to the column data type
(GetXmlFullPath(strXsdPath));
(GetXmlFullPath(strXmlPath));
DataTable dt = [0];
//Create a new row based on the original table
DataRow newRow = ();
//Loop to assign values to each column in a row
for(int i=0; i〈 ; i++)
{
newRow[Columns[i]] = ColumnValue[i];
}
(newRow);
();
();
(GetXmlFullPath(strXmlPath));
return true;
}
catch(Exception)
{
return false;
}
}
#endregion
Some friends may not know how to use this method to insert data, I will introduce it with examples later.
(5) Modify records
There are relatively many parameters to be passed in when modifying records, because modifying records requires first positioning which record is then modified, and then modifying the value of the specified column. The following is the method of modifying XML:
#region UpdateXmlRow
/// 〈summary〉
/// More Xml record that meets the criteria
/// 〈/summary〉
/// 〈param name="strXmlPath"〉XML file path〈/param〉
/// 〈param name="Columns"〉Column name array〈/param〉
/// 〈param name="ColumnValue">Column value array〈/param〉
/// 〈param name="strWhereColumnName"> conditional column name〈/param〉
/// 〈param name="strWhereColumnValue"> condition column value </param>
/// 〈returns〉〈/returns〉
public static bool UpdateXmlRow(string strXmlPath,string[] Columns,string[] ColumnValue,string strWhereColumnName,string strWhereColumnValue)
{
try
{
//Same method as above
string strXsdPath = (0,(".")) + ".xsd";
DataSet ds = new DataSet();
//Read the xml schema, related to the column data type
(GetXmlFullPath(strXsdPath));
(GetXmlFullPath(strXmlPath));
//Judge the number of rows first
if([0]. 〉 0)
{
for(int i=0; i〈 [0].; i++)
{
//If the current record is a record that meets the Where condition if([0].Rows[i][strWhereColumnName].ToString().Trim().Equals(strWhereColumnValue))
{
//Loop assign new values to each column that finds row
for(int j=0; j 〈 ; j++)
{
[0].Rows[i][Columns[j]] = ColumnValue[j];
}
//Update DataSet
();
//Rewrite to XML file
(GetXmlFullPath(strXmlPath));
return true;
}
}
}
return false;
}
catch(Exception)
{
return false;
}
}
#endregion
(6) Delete records
For convenience, deleting records provides three methods, one can delete all records, one can delete rows that meet the criteria, and one can delete rows that specify the Index value and record in Data
The Index value in Set corresponds to. The method to delete all records is:
#region DeleteXmlAllRows
/// 〈summary〉
/// Delete all rows
/// 〈/summary〉
/// 〈param name="strXmlPath"〉XML path〈/param〉
/// 〈returns〉〈/returns〉
public static bool DeleteXmlAllRows(string strXmlPath)
{
try
{
DataSet ds = new DataSet();
(GetXmlFullPath(strXmlPath));
//If the number of records is greater than 0
if([0]. 〉 0)
{
//Remove all records
[0].();
}
//Rewrite, then only the root node is left in the XML file
(GetXmlFullPath(strXmlPath));
return true;
}
catch(Exception)
{
return false;
}
}
#endregion
The method to delete the row with the specified Index value is:
#region DeleteXmlRowByIndex
/// 〈summary〉
/// Delete the iDeleteRow line in DataSet and then rewrite Xml to delete the specified line
/// 〈/summary〉
/// 〈param name="strXmlPath"〉〈/param〉
/// 〈param name="iDeleteRow"〉The Index value of the row to be deleted in the DataSet </param>
public static bool DeleteXmlRowByIndex(string strXmlPath,int iDeleteRow)
{
try
{
DataSet ds = new DataSet();
(GetXmlFullPath(strXmlPath));
if([0]. 〉 0)
{
//Delete the line of the symbol condition
[0].Rows[iDeleteRow].Delete();
}
(GetXmlFullPath(strXmlPath));
return true;
}
catch(Exception)
{
return false;
}
}
#endregion
Here we will talk about the reason for providing this method. Sometimes, after reading the XML content to the DataSet and then binding it to DataGrid, since there is only one template column in the DataGrid, and many other controls are covered with tables and other controls, this makes it impossible for us to get the corresponding ID value of the record. At this time, we can first get the index value of the record (the first behavior is 0, the second behavior is 1, and so on), and then pass the Index value to the method to delete the record.
Note: When using this method, the DataSet bound to DataGrid and the DataSet used for deletion should be the same, that is, the Index should be the same and there should be no sorting, otherwise the record will be mistakenly recorded.
Sometimes we need to delete multiple rows that meet the conditions. At this time, we can use the following method to implement it:
#region DeleteXmlRows
/// 〈summary〉
/// Delete the row with the value of ColumnValue in the strColumn column
/// 〈/summary〉
/// 〈param name="strXmlPath"〉xml relative path〈/param〉
/// 〈param name="strColumn"〉Column name〈/param〉
/// 〈param name="ColumnValue"〉Lines with Column column value of ColumnValue will be deleted〈/param〉
/// 〈returns〉〈/returns〉
public static bool DeleteXmlRows(string strXmlPath,string strColumn,string[] ColumnValue)
{
try
{
DataSet ds = new DataSet();
(GetXmlFullPath(strXmlPath));
//Judge the number of rows first
if([0]. 〉 0)
{
//Judge whether there are many rows or deleted values, put the more for loops in it
if( 〉 [0].)
{
for(int i=0; i 〈 [0].; i++)
{
for(int j=0; j 〈 ; j++)
{
//Find the line that meets the criteria if([0].Rows[i][strColumn].ToString().Trim().Equals(ColumnValue[j]))
{
//Delete the line
[0].Rows[i].Delete();
}
}
}
}
else
{
for(int j=0; j 〈 ; j++)
{
for(int i=0; i 〈 [0].; i++)
{
//Find the line that meets the criteria if([0].Rows[i][strColumn].ToString().Trim().Equals(ColumnValue[j]))
{
//Delete the line
[0].Rows[i].Delete();
}
}
}
}
(GetXmlFullPath(strXmlPath));
}
return true;
}
catch(Exception)
{
return false;
}
}
#endregion
3 instance analysis
(7) Read XML
The following code reads to a DataSet that is not sorted and filtered.
= (@"xml/xml_xmlDB.xml");
();
The following code reads data that is filtered and sorted:
= (
@"xml/xml_xmlDB.xml", //XML file path
"name = '/", //condition: the name column value is
"peopleNum desc"); //Sort in descending order of peopleNum column
();
(8) Add records
The following code adds a record to the XML file and assigns values to 7 columns at the same time:
bool b;
b = (
@"xml/xml_xmlDB.xml", //XML file address
new string[]{
"name", //Name field
"peopleNum", //PeopleNum
"address", //Address field
"description", //Description field
"require", //Requirement field
"deadLine", //End time field
"IsMarried" //Marriage field
},
new string[]{
"Programmer", //Name field value
"2", //People number field value
"Jianguo Road", //Address field value
"B/S structure program", //Describe field value
"c#, etc.", //Required field value
(), //End time field value
"false" //Marriage field value
});
If the return value of b is true, it means the addition is successful, otherwise it means the addition has failed. I used some lazy methods to write the above method, such as I placed the array directly on the parameters without further declaration. In fact, you can declare another array and then pass it into the method.
Note the correspondence between the position of the field in the array and the position of the value in the array.
(9) Modify records
The following code will find the row with a column value of 3 for peopleNum, and then update the values of the row's name, peopleNum, description and IsMarried fields to kgdiwss, 10, description and true respectively.
bool b;
b = (
@"xml/xml_xmlDB.xml",
new string[]{"name","peopleNum","description","IsMarried"},
new string[]{"kgdiwss", "10", "description", "true"},
"peopleNum",
"3");
Returning true means the modification is successful, otherwise it means the modification is failed.
Please note that when the field type is logical, the assignment uses true and false, rather than 0 and 1.
(10) Delete records
The following code implements the deletion of rows whose name column values are values in the array.
bool b;
b = (
@"xml/xml_xmlDB.xml", //XML file path
"name", //condition column
new string[]{
"Value 1", //Conditional value 1
"Value 2", //Conditional value 2
"Value 3" // Conditional value 3
});
After the above code is successfully executed, rows with values of value 1, value 2, and value 3 will be deleted.
Return true if the deletion is successful, otherwise return false.
The other two methods of deletion are relatively simple to use, so I won't introduce them here.
The above are all the methods of operating XML, which I believe can satisfy a large part of the use. However, if the amount of data in XML is relatively large, the efficiency of using the above methods may not be high, but then again, if the amount of data is relatively large, it is better to choose a database.
Previous page12Read the full text