C # XML Code List (read XML, write XML, update, delete nodes, and combine with dataset) page 1/2

Source: Internet
Author: User

It is known that there is an XML file (bookstore. XML) as follows:
Corets, Eva
5.95
1. Insert nodes
Insert a node to the node: CopyCode The Code is as follows: xmldocument xmldoc = new xmldocument ();
Xmldoc. Load ("Bookstore. xml ");
Xmlnode root = xmldoc. selectsinglenode ("Bookstore"); // search
Xmlelement xe1 = xmldoc. createelement ("book"); // create a node
Xe1.setattribute ("genre", "lizan red"); // you can specify the genre attribute of the node.
Xe1.setattribute ("ISBN", "2-3631-4"); // you can specify the ISBN attribute of the node.

Xmlelement xesub1 = xmldoc. createelement ("title ");
Xesub1.innertext = "Cs from entry to entry"; // set a 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 ");

Result:
Corets, Eva
5.95
Hou Jie
58.3
2. Modify nodes:
Change the genre value of the node whose genre attribute value is "lizan red" to "Update lizan red", and change the text of the child node of the node to "Yasheng ".

Copy code The Code is as follows: xmlnodelist nodelist = xmldoc. selectsinglenode ("Bookstore"). childnodes; // obtain all the subnodes of the bookstore Node
Foreach (xmlnode Xn in nodelist) // traverses all subnodes
{
Xmlelement Xe = (xmlelement) xn; // converts the subnode type to the xmlelement type
If (Xe. getattribute ("genre") = "") // If the genre attribute value is ""
{
Xe. setattribute ("genre", "Update lizan red"); // you can change this attribute to "Update lizan red"

Xmlnodelist NLS = Xe. childnodes; // continue to obtain all the child nodes of the Xe subnode
Foreach (xmlnode xn1 in NLS) // traverse
{
Xmlelement xe2 = (xmlelement) xn1; // Conversion Type
If (xe2.name = "author") // If you find
{
Xe2.innertext = "Yasheng"; // modify
Break; // find and exit.
}
}
Break;
}
}
Xmldoc. Save ("Bookstore. xml"); // save.

The final result is:
Corets, Eva
5.95
Yasheng
58.3
3. delete a node
Delete the genre attribute of a node.

Copy code The Code is 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 attributes
}
Else if (Xe. getattribute ("genre") = "Update lizanhong ")
{
Xe. removeall (); // delete all content of the node
}
}
Xmldoc. Save ("Bookstore. xml ");

The final result is:
Corets, Eva
5.95
4. display all data.

Copy code The Code is 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 attribute values
Console. writeline (Xe. getattribute ("ISBN "));

Xmlnodelist xnf1 = Xe. childnodes;
Foreach (xmlnode xn2 in xnf1)
{
Console. writeline (xn2.innertext); // displays the child node text.
}
}

Loading...

A class that uses dataset to operate XML (Source code)

Copy codeThe Code is as follows: using system;
Using system. Data;
Using system. xml;
Using system. Windows. forms;

//************************************** *
// Prepared by: # go to dinner tomorrow
// Qicq: 305725744
//. Net group: 6370988
// Http://blog.csdn.net/kgdiwss
//************************************** *

Namespace ystrp. Common
{
///
/// Operatexmlbydataset abstract description.
///
Public class operatexmlbydataset
{
Public operatexmlbydataset ()
{
//
// Todo: add the constructor logic here
//
}

# Region getdatasetbyxml
///
/// Read XML and return dataset directly
///
/// Relative path of the XML file
///
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 the XML and return a sorted or filtered dataview.
///
///
/// Filter conditions, such as: "name = 'kgdiwss '"
/// Sorting condition, for example, "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
///
/// Insert a row of data into the XML file
///
/// Relative path of the XML file
/// Array of column names to insert rows, for example, string [] Columns = {"name", "ismarried "};
/// Array of values in each column of the row to be inserted, for example, string [] columnvalue = {"coming tomorrow", "false "};
/// If the call succeeds, true is returned. Otherwise, false is returned.
Public static bool writexmlbydataset (string strxmlpath, string [] columns, string [] columnvalue)
{
Try
{
// Obtain the. XSD path based on the input XML Path. The two files are stored in the same directory.
String strxsdpath = strxmlpath. substring (0, strxmlpath. indexof (".") + ". XSD ";

Dataset DS = new dataset ();
// Read the XML schema, which is related to the column data type
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 ();

// Cyclically assign values to each column 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
///
/// A qualified XML record for a row
///
/// XML file path
/// Array of column names
/// Array of column values
/// Condition column name
/// Condition column Value
///
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 the XML schema, which is related to the column data type
DS. readxmlschema (getxmlfullpath (strxsdpath ));
DS. readxml (getxmlfullpath (strxmlpath ));

// Determine 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 meets the where Condition
If (Ds. Tables [0]. Rows [I] [strwherecolumnname]. tostring (). Trim (). Equals (strwherecolumnvalue ))
{
// Cyclically add new values to columns of the row
For (Int J = 0; j <columns. length; j ++)
{
DS. Tables [0]. Rows [I] [columns [J] = columnvalue [J];
}
// Update Dataset
DS. acceptchanges ();
// Re-write the XML file
DS. writexml (getxmlfullpath (strxmlpath ));
Return true;
}
}

}
Return false;
}
Catch (exception)
{
Return false;
}
}
# Endregion

# Region deletexmlrowbyindex
///
/// Delete the ideleterow row in dataset, and then rewrite the XML to delete the specified row.
///
///
/// Index value of the row to be deleted in 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 the row of the symbol Condition
DS. Tables [0]. Rows [ideleterow]. Delete ();
}
DS. writexml (getxmlfullpath (strxmlpath ));
Return true;
}
Catch (exception)
{
Return false;
}
}
# Endregion

# Region deletexmlrows
///
/// Delete the row whose value is columnvalue in the strcolumn
///
/// Relative XML Path
/// Column name
/// All rows whose values are columnvalue will be deleted.
///
Public static bool deletexmlrows (string strxmlpath, string strcolumn, string [] columnvalue)
{
Try
{
Dataset DS = new dataset ();
DS. readxml (getxmlfullpath (strxmlpath ));

// determine the number of rows first
If (Ds. tables [0]. rows. count> 0)
{< br> // you can determine whether there are multiple rows or Deleted Values. If (columnvalue. length> DS. tables [0]. rows. count)
{< br> for (INT I = 0; I {< br> for (Int J = 0; j {< br> If (Ds. tables [0]. rows [I] [strcolumn]. tostring (). trim (). equals (columnvalue [J])
{< br> DS. tables [0]. rows [I]. delete ();
}< BR >}< br> else
{< br> for (Int J = 0; j {< br> for (INT I = 0; I {< br> If (Ds. tables [0]. rows [I] [strcolumn]. tostring (). trim (). equals (columnvalue [J])
{< br> DS. tables [0]. rows [I]. delete ();
}< BR >}< br> DS. writexml (getxmlfullpath (strxmlpath);
}< br> return true;
}< br> catch (exception)
{< br> return false;
}< BR ># 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 number of records is greater than 0
If (Ds. Tables [0]. Rows. Count> 0)
{
// Remove all records
DS. Tables [0]. Rows. Clear ();
}
// Re-write. At this time, only the root node is left in the XML file.
DS. writexml (getxmlfullpath (strxmlpath ));
Return true;
}
Catch (exception)
{
Return false;
}
}
# Endregion

# Region getxmlfullpath
///
/// Return the complete path
///
/// XML Path
///
Public static string getxmlfullpath (string strpath)
{
If (strpath. indexof (":")> 0)
{
Return strpath;
}
Else
{
Return application. startuppath + strpath;
}
}
# Endregion
}
}

Loading...

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.