C # XML Operation code Encyclopedia (read XML, write XML, update, delete node, combine with DataSet, etc.) 1th/2 page _ Practical Tips

Source: Internet
Author: User
An XML file (Bookstore.xml) is known as follows:
Corets, Eva
5.95
1. Insert Node
To insert a node into a node:
Copy Code code as follows:

XmlDocument xmldoc=new XmlDocument ();
Xmldoc.load ("Bookstore.xml");
XmlNode Root=xmldoc.selectsinglenode ("bookstore")/Find
XmlElement xe1=xmldoc.createelement ("book");//Create a node
Xe1. SetAttribute ("Genre", "Li Zhanhong");/set the node genre property
Xe1. SetAttribute ("ISBN", "2-3631-4");//Set the node ISBN property

XmlElement xesub1=xmldoc.createelement ("title");
Xesub1. Innertext= "CS from getting started to proficient";/Set Text node
Xe1. AppendChild (XESUB1);//Add to Node
XmlElement xesub2=xmldoc.createelement ("author");
Xesub2. innertext= "Hou Jie";
Xe1. AppendChild (XESUB2);
XmlElement xesub3=xmldoc.createelement ("price");
Xesub3. innertext= "58.3";
Xe1. AppendChild (XESUB3);

Root. AppendChild (XE1);//Add to Node
Xmldoc.save ("Bookstore.xml");

The results are:
Corets, Eva
5.95
Hou Jie
58.3
2, modify the node:
Change the genre value of the node with the genre property value "Li Zhanhong" to "Update Li Zhanhong" and modify the text of the node's child nodes to "Asian wins."

Copy Code code as follows:

XmlNodeList Nodelist=xmldoc.selectsinglenode ("bookstore"). childnodes;//gets all the child nodes of the bookstore node
foreach (XmlNode xn in nodelist)//traverse all child nodes
{
XmlElement xe= (XmlElement) xn;//Converts a child node type to a XmlElement type
if (XE. GetAttribute ("genre") = = "Li Zhanhong")//If genre property value is "Li Zhanhong"
{
Xe. SetAttribute ("Genre", "Update Li Zhanhong");//Modify this property to "Update Li Zhanhong"

XmlNodeList Nls=xe. CHILDNODES;//continues to fetch all child nodes of the XE child node
foreach (XmlNode xn1 in NLS)//traversal
{
XmlElement xe2= (XmlElement) xn1;//conversion type
if (Xe2. name== "Author")//If found
{
Xe2. innertext= "Asia wins";//Modify
break;//find out and get out of here.
}
}
Break
}
}
Xmldoc.save ("Bookstore.xml"),//save.

The final results are:
Corets, Eva
5.95
Asia wins
58.3
3, delete the node
The genre property of the node to delete the node.

Copy Code code as follows:

XmlNodeList Xnl=xmldoc.selectsinglenode ("bookstore"). ChildNodes;

foreach (XmlNode xn in xnl)
{
XmlElement xe= (XmlElement) xn;
if (XE. GetAttribute ("genre") = = "Fantasy")
{
Xe. RemoveAttribute ("genre");//Delete genre property
}
else if (XE. GetAttribute ("genre") = = "Update Li Zhanhong")
{
Xe. RemoveAll ()//delete all contents of the node
}
}
Xmldoc.save ("Bookstore.xml");

The final results are:
Corets, Eva
5.95
4, display all the data.

Copy Code code as follows:

XmlNode Xn=xmldoc.selectsinglenode ("bookstore");

XmlNodeList Xnl=xn. ChildNodes;

foreach (XmlNode xnf in XNL)
{
XmlElement xe= (XmlElement) xnf;
Console.WriteLine (XE. GetAttribute ("genre"))//Display property value
Console.WriteLine (XE. GetAttribute ("ISBN"));

XmlNodeList Xnf1=xe. ChildNodes;
foreach (XmlNode xn2 in Xnf1)
{
Console.WriteLine (xn2. innertext);//Display child node point text
}
}

Loading ...


A class that operates XML through a dataset (source code)


Copy Code code as follows:

Using System;
Using System.Data;
Using System.Xml;
Using System.Windows.Forms;

//***************************************
The writer: go begging tomorrow
qicq:305725744
// . NET group: 6370988
Http://blog.csdn.net/kgdiwss
//***************************************

Namespace Ystrp.common
{
///
Summary description of the Operatexmlbydataset.
///
public class Operatexmlbydataset
{
Public Operatexmlbydataset ()
{
//
TODO: Add constructor logic here
//
}

#region Getdatasetbyxml
///
Read XML to return dataset directly
///
XML file relative path
///
public static DataSet Getdatasetbyxml (String strxmlpath)
{
Try
{
DataSet ds = new DataSet ();
Ds. READXML (Getxmlfullpath (Strxmlpath));
if (ds. Tables.count > 0)
{
return DS;
}
return null;
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show (ex. ToString ());
return null;
}
}
#endregion
#region Getdataviewbyxml
///
Read XML returns a sorted or filtered DataView
///
///
Filter criteria, such as: "name = ' Kgdiwss '"
Sort criteria, such as: "Id desc"
///
public static DataView Getdataviewbyxml (string strxmlpath,string strwhere,string strsort)
{
Try
{
DataSet ds = new DataSet ();
Ds. READXML (Getxmlfullpath (Strxmlpath));
DataView dv = new DataView (ds. Tables[0]);
if (strsort!= null)
{
Dv. Sort = StrSort;
}
if (strwhere!= null)
{
Dv. RowFilter = strwhere;
}
return DV;
}
catch (Exception)
{
return null;
}
}
#endregion


#region Writexmlbydataset
///
Inserting a row of data into an XML file
///
XML file relative path
Column array group to insert row, such as: string[] Columns = {"Name", "Ismarried"};
An array of values to insert rows per column, such as: string[] columnvalue={"Go begging Tomorrow", "false"};
Returns true successfully, otherwise returns false
public static bool Writexmlbydataset (string strxmlpath,string[] columns,string[] columnvalue)
{
Try
{
Gets the path to the. xsd based on the incoming XML path, with two files in the same directory
String strxsdpath = Strxmlpath.substring (0,strxmlpath.indexof (".")) + ". xsd";

DataSet ds = new DataSet ();
Read XML schemas, related to the data types of columns
Ds. ReadXmlSchema (Getxmlfullpath (Strxsdpath));
Ds. READXML (Getxmlfullpath (Strxmlpath));
DataTable dt = ds. Tables[0];
Create a new row based on the original table
DataRow newrow = dt. NewRow ();

Loop to assign values to individual columns in a row
for (int i=0; i< columns.length; i++)
{
Newrow[columns[i]] = columnvalue[i];
}
Dt. Rows.Add (NewRow);
Dt. AcceptChanges ();
Ds. AcceptChanges ();

Ds. WriteXml (Getxmlfullpath (Strxmlpath));
return true;
}
catch (Exception)
{
return false;
}
}
#endregion


#region Updatexmlrow
///
An XML record that meets the criteria in a row
///
XML file path
Column array Group
Array of column values
Condition Column Name
Conditional column Values
///
public static bool Updatexmlrow (string strxmlpath,string[] columns,string[] columnvalue,string strwherecolumnname, String strwherecolumnvalue)
{
Try
{
String strxsdpath = Strxmlpath.substring (0,strxmlpath.indexof (".")) + ". xsd";

DataSet ds = new DataSet ();
Read XML schemas, related to the data types of columns
Ds. ReadXmlSchema (Getxmlfullpath (Strxsdpath));
Ds. READXML (Getxmlfullpath (Strxmlpath));

Judge the number of rows first
if (ds. Tables[0]. Rows.Count > 0)
{
for (int i=0; i< ds. Tables[0]. Rows.Count; i++)
{
If the current record is a record that matches the Where condition
if (ds. Tables[0]. Rows[i][strwherecolumnname]. ToString (). Trim (). Equals (Strwherecolumnvalue))
{
Loops to assign new values to columns that find rows
for (int j=0 J < Columns.length; J + +)
{
Ds. Tables[0]. ROWS[I][COLUMNS[J]] = columnvalue[j];
}
Update DataSet
Ds. AcceptChanges ();
Re-write XML file
Ds. WriteXml (Getxmlfullpath (Strxmlpath));
return true;
}
}

}
return false;
}
catch (Exception)
{
return false;
}
}
#endregion


#region Deletexmlrowbyindex
///
Ideleterow this line by deleting the dataset, and then rewriting the XML to implement the delete specified row
///
///
The index value of the row to delete in the dataset
public static bool Deletexmlrowbyindex (String Strxmlpath,int ideleterow)
{
Try
{
DataSet ds = new DataSet ();
Ds. READXML (Getxmlfullpath (Strxmlpath));
if (ds. Tables[0]. Rows.Count > 0)
{
Delete a line of symbol criteria
Ds. Tables[0]. Rows[ideleterow]. Delete ();
}
Ds. WriteXml (Getxmlfullpath (Strxmlpath));
return true;
}
catch (Exception)
{
return false;
}
}
#endregion


#region Deletexmlrows
///
Delete a row in the Strcolumn column with a value of Columnvalue
///
XML relative path
Column Name
Rows with Columnvalue values in the Strcolumn column are deleted
///
public static bool Deletexmlrows (String strxmlpath,string strcolumn,string[] columnvalue)
{
Try
{
DataSet ds = new DataSet ();
Ds. READXML (Getxmlfullpath (Strxmlpath));

Judge the number of rows first
if (ds. Tables[0]. Rows.Count > 0)
{
To judge whether the row is more or deleted, the more for loop is placed inside
if (Columnvalue.length > ds. Tables[0]. Rows.Count)
{
for (int i=0 i < ds.) Tables[0]. Rows.Count; i++)
{
for (int j=0 J < Columnvalue.length; J + +)
{
if (ds. Tables[0]. Rows[i][strcolumn]. ToString (). Trim (). Equals (Columnvalue[j])
{
Ds. Tables[0]. Rows[i]. Delete ();
}
}
}
}
Else
{
for (int j=0 J < Columnvalue.length; J + +)
{
for (int i=0 i < ds.) Tables[0]. Rows.Count; i++)
{
if (ds. Tables[0]. Rows[i][strcolumn]. ToString (). Trim (). Equals (Columnvalue[j])
{
Ds. Tables[0]. Rows[i]. Delete ();
}
}
}
}
Ds. WriteXml (Getxmlfullpath (Strxmlpath));
}
return true;
}
catch (Exception)
{
return false;
}
}
#endregion


#region Deletexmlallrows
///
Delete all rows
///
XML Path
///
public static bool Deletexmlallrows (string Strxmlpath)
{
Try
{
DataSet ds = new DataSet ();
Ds. READXML (Getxmlfullpath (Strxmlpath));
If the record bar number is greater than 0
if (ds. Tables[0]. Rows.Count > 0)
{
Remove all records
Ds. Tables[0]. Rows.clear ();
}
Re-write, when the root node is left in the XML file
Ds. WriteXml (Getxmlfullpath (Strxmlpath));
return true;
}
catch (Exception)
{
return false;
}
}
#endregion


#region Getxmlfullpath
///
Return full path
///
Path to XML
///
public static string Getxmlfullpath (String strpath)
{
if (Strpath.indexof (":") > 0)
{
return strpath;
}
Else
{
return Application.startuppath + strpath;
}
}
#endregion
}
}

Loading ...
Current 1/2 page 12 Next read the full text
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.