asp.net XML operation method and XML Operation class

Source: Internet
Author: User
Tags net xml table name

Program generates XML document
This approach is to use a C # program to generate an XML file and place the data in it for processing. Here are a few different ways to achieve the same goal.

Simple example of using the XmlWriter class to edit data:

The code is as follows Copy Code
XmlTextWriter xtw = new XmlTextWriter (FilePath, Encoding.UTF8);
Xtw. formatting = formatting.indented;
Xtw. WriteStartDocument (TRUE);
Xtw. WriteStartElement ("root");
Xtw. WriteElementString ("username", nodevalue);
Xtw. WriteEndElement ();
Xtw. WriteEndDocument ();
Xtw. Flush ();
Xtw. Close ();

In the sample code, the code is slightly nodevalue for the data value obtained. FilePath is the XML file path value, the code is slightly.

The result of the run is to generate an XML document with the same content as the previous text.

Examples implemented with the XmlDocument class:

The code is as follows Copy Code

XmlDocument xmldoc;
XmlDeclaration xmldecl;
XmlNode XmlNode;
XmlElement Xmlelem;

xmldoc = new XmlDocument ();
Xmldecl = xmldoc. Createxmldeclaration ("1.0", "gb2312", null);
XmlDoc. AppendChild (XMLDECL);
Xmlelem = xmldoc. CreateElement ("", "Root", "");
XmlDoc. AppendChild (Xmlelem);
XmlNode = xmldoc. CreateElement ("username");
XmlNode. innertext = NodeValue;
Xmlelem. AppendChild (XmlNode);
XmlDoc. Save (FilePath);

Note: Because the XmlDocument class is implemented, the performance is less efficient than the XmlWriter class implementation. So it is recommended to use the XmlWriter class to implement.

Implemented using XML serialization techniques:

The code is as follows Copy Code
Root root = new root ();
Root. Username = NodeValue;
XmlSerializer srl = new XmlSerializer (typeof (Root));
StreamWriter wrt = new StreamWriter (FilePath);
Srl. Serialize (wrt, root);
Wrt. Close ();

The complete contents of the root class are as follows:

  code is as follows copy code

using System;

Public class Root
{
    private string _username
    public string username
    {
        get
         {
            return _username
        }
        set
         {
            _username = value ;
       }
   }
}

Operation of an existing XML document
If you are working with an existing XML document file, instead of using a program to generate a new XML document file? The following example is a partial fragment of the C # programming code:

The code is as follows Copy Code
XmlDocument xmldoc = new XmlDocument ();
XmlDoc. Load (FilePath);
XmlNodeList XmlNodeList = xmldoc. selectSingleNode ("Root"). ChildNodes;
foreach (XmlNode XmlNode in XmlNodeList)
{
while (XmlNode. Name = = "Username")
{
XmlNode. innertext = NodeValue;
Break
}
}
XmlDoc. Save (FilePath);

Code is working with an existing XML file, you can look at the following example of a program in the constructor method of a class:

The code is as follows Copy Code
if (file.exists (FilePath))
{
Xmloperatehandle ();
}
Else
{
Xmlwriterhandle ();
}

To improve the performance of the program, we use XPathNavigator object processing to modify the rewrite:

The code is as follows Copy Code

XmlDocument xmldoc = new XmlDocument ();
try {xmldoc. Load (FilePath); }
Catch {}
XPathNavigator navigator = xmldoc. CreateNavigator ();
Navigator. MoveToRoot ();
if (navigator. HasChildren)
{
Navigator. MoveToFirstChild ();
if (navigator. Name = = "username")
{
Navigator. INNERXML = NodeValue;
}
}

Here we write the XML as a class

The code is as follows Copy Code

Using System;
Using System.Xml;
Using System.Data;

Namespace Xmlclass
{
<summary>
XML-related common functionality
</summary>
public class Xmlhelper
{
Public Xmlhelper () {}

<summary>
XML Resource Type
</summary>
public enum XmlType
{
File,
String
};

#region reading XML resources into the dataset
<summary>
Reading XML resources into the dataset
</summary>
<param name= "source" >xml resource, file is path, otherwise XML string </param>
<param name= "XmlType" >xml resource type </param>
<returns>DataSet</returns>
public static DataSet GetDataSet (string source, XmlType XmlType)
{
DataSet ds = new DataSet ();
if (XmlType = = xmltype.file)
{
Ds. READXML (source);
}
Else
{
XmlDocument xd = new XmlDocument ();
Xd. Loadxml (source);
XmlNodeReader Xnr = new XmlNodeReader (XD);
Ds. READXML (XNR);
}
return DS;
}

#endregion

#region Get the DS in a string XML document
<summary>
Gets the DS in a string XML document
</summary>
<param name= "xml_string" > Strings containing XML information </param>
public static void Get_xmlvalue_ds (string xml_string, ref DataSet DS)
{
System.Xml.XmlDocument xd = new XmlDocument ();
Xd. Loadxml (xml_string);
XmlNodeReader Xnr = new XmlNodeReader (XD);
Ds. READXML (XNR);
Xnr. Close ();
int a = ds. Tables.count;
}
#endregion

#region reading XML resources into the DataTable
<summary>
Reading XML resources into the DataTable
</summary>
<param name= "source" >xml resource, file is path, otherwise XML string </param>
<param name= "XmlType" >xml Resource type: file, String </param>
<param name= "tablename" > table name </param>
<returns>DataTable</returns>
public static DataTable GetTable (string source, XmlType XmlType, string tablename)
{
DataSet ds = new DataSet ();
if (XmlType = = xmltype.file)
{
Ds. READXML (source);
}
Else
{
XmlDocument xd = new XmlDocument ();
Xd. Loadxml (source);
XmlNodeReader Xnr = new XmlNodeReader (XD);
Ds. READXML (XNR);
}
Return DS. Tables[tablename];
}
#endregion

The value of the specified column #region reading the specified row of the specified DataTable in the XML resource
<summary>
Reads the value of the specified column in the specified row of the specified DataTable in the XML resource
</summary>
<param name= "source" >xml Resources </param>
<param name= "XmlType" >xml Resource type: file, String </param>
<param name= "tablename" > table name </param>
<param name= "RowIndex" > Line number </param>
<param name= "colname" > Column name </param>
<returns> value, return null</returns> when not present
public static object Gettablecell (string source, XmlType XmlType, string tablename, int rowIndex, string colname)
{
DataSet ds = new DataSet ();
if (XmlType = = xmltype.file)
{
Ds. READXML (source);
}
Else
{
XmlDocument xd = new XmlDocument ();
Xd. Loadxml (source);
XmlNodeReader Xnr = new XmlNodeReader (XD);
Ds. READXML (XNR);
}
Return DS. Tables[tablename]. Rows[rowindex][colname];
}
#endregion

The value of the specified column #region reading the specified row of the specified DataTable in the XML resource
<summary>
Reads the value of the specified column in the specified row of the specified DataTable in the XML resource
</summary>
<param name= "source" >xml Resources </param>
<param name= "XmlType" >xml Resource type: file, String </param>
<param name= "tablename" > table name </param>
<param name= "RowIndex" > Line number </param>
<param name= "Colindex" > Column number </param>
<returns> value, return null</returns> when not present
public static object Gettablecell (string source, XmlType XmlType, string tablename, int rowIndex, int colindex)
{
DataSet ds = new DataSet ();
if (XmlType = = xmltype.file)
{
Ds. READXML (source);
}
Else
{
XmlDocument xd = new XmlDocument ();
Xd. Loadxml (source);
XmlNodeReader Xnr = new XmlNodeReader (XD);
Ds. READXML (XNR);
}
Return DS. Tables[tablename]. Rows[rowindex][colindex];
}
#endregion

#region writes a DataTable to an XML file
<summary>
To write a DataTable into an XML file
</summary>
<param name= "DT" > datatable</param> containing data
<param name= "FilePath" > File path </param>
public static void Savetabletofile (DataTable dt, string filePath)
{
DataSet ds = new DataSet ("Config");
Ds. Tables.add (dt. Copy ());
Ds. WriteXml (FilePath);
}
#endregion

#region writes a DataTable to a file with the specified root node name
<summary>
Writes a DataTable to a file with the specified root node name
</summary>
<param name= "DT" > datatable</param> containing data
<param name= "Rootname" > Root node name </param>
<param name= "FilePath" > File path </param>
public static void Savetabletofile (DataTable dt, String rootname, String filePath)
{
DataSet ds = new DataSet (Rootname);
Ds. Tables.add (dt. Copy ());
Ds. WriteXml (FilePath);
}
#endregion

To update an XML file node #region using a dataset
<summary>
Updating an XML file node with a dataset method
</summary>
<param name= "FilePath" >xml file path </param>
<param name= "tablename" > table name </param>
<param name= "RowIndex" > Line number </param>
<param name= "colname" > Column name </param>
<param name= "Content" > Update value </param>
<returns> whether the update was successful </returns>
public static bool Updatetablecell (string FilePath, string tablename, int rowIndex, string colname, string content)
{
BOOL flag = FALSE;
DataSet ds = new DataSet ();
Ds. READXML (FilePath);
DataTable dt = ds. Tables[tablename];

if (dt. Rows[rowindex][colname]!= null)
{
Dt. Rows[rowindex][colname] = content;
Ds. WriteXml (FilePath);
Flag = true;
}
Else
{
Flag = false;
}
return flag;
}
#endregion

To update an XML file node #region using a dataset
<summary>
Updating an XML file node with a dataset method
</summary>
<param name= "FilePath" >xml file path </param>
<param name= "tablename" > table name </param>
<param name= "RowIndex" > Line number </param>
<param name= "Colindex" > Column number </param>
<param name= "Content" > Update value </param>
<returns> whether the update was successful </returns>
public static bool Updatetablecell (string FilePath, string tablename, int rowIndex, int colindex, string content)
{
BOOL flag = FALSE;

DataSet ds = new DataSet ();
Ds. READXML (FilePath);
DataTable dt = ds. Tables[tablename];

if (dt. Rows[rowindex][colindex]!= null)
{
Dt. Rows[rowindex][colindex] = content;
Ds. WriteXml (FilePath);
Flag = true;
}
Else
{
Flag = false;
}
return flag;
}
#endregion

#region Read the contents of a specified node in an XML resource
<summary>
Reading the contents of a specified node in an XML resource
</summary>
<param name= "source" >xml Resources </param>
<param name= "XmlType" >xml Resource type: file, String </param>
<param name= "NodeName" > Node name </param>
<returns> node Content </returns>
public static object Getnodevalue (string source, XmlType XmlType, String nodename)
{
XmlDocument xd = new XmlDocument ();
if (XmlType = = xmltype.file)
{
Xd. Load (source);
}
Else
{
Xd. Loadxml (source);
}
XmlElement XE = xd. DocumentElement;
XmlNode xn = Xe. selectSingleNode ("//" + nodename);
if (xn!= null)
{
Return xn. InnerText;
}
Else
{
return null;
}
}

<summary>
Reading the contents of a specified node in an XML resource
</summary>
<param name= "source" >xml Resources </param>
<param name= "NodeName" > Node name </param>
<returns> node Content </returns>
public static object Getnodevalue (string source, String nodename)
{
if (Source = null | | nodename = NULL | | source = = "" | | nodename = "" | | Source. Length < Nodename.length * 2)
{
return null;
}
Else
{
int start = source. IndexOf ("<" + NodeName + ">") + nodename.length + 2;
int end = source. IndexOf ("</" + nodename + ">");
if (start = = 1 | | end = = 1)
{
return null;
}
else if (start >= end)
{
return null;
}
Else
{
return source. Substring (start, End-start);
}
}
}
#endregion

#region Update the contents of a specified node in an XML file
<summary>
Update the contents of the specified node in the XML file
</summary>
<param name= "FilePath" > File path </param>
<param name= "NodeName" > Node name </param>
<param name= "NodeValue" > Update content </param>
<returns> whether the update was successful </returns>
public static bool Updatenode (string FilePath, String nodename, String nodevalue)
{
BOOL flag = FALSE;

XmlDocument xd = new XmlDocument ();
Xd. Load (FilePath);
XmlElement XE = xd. DocumentElement;
XmlNode xn = Xe. selectSingleNode ("//" + nodename);
if (xn!= null)
{
Xn. innertext = NodeValue;
Flag = true;
}
Else
{
Flag = false;
}
return flag;
}
#endregion

#region manipulating data from a specified node in an XML file
<summary>
Gets the node data for the specified node in the XML file
</summary>
<param name= "tablename" ></param>
<returns></returns>
public static string Getnodeinfobynodename (string path, String nodename)
{
String xmlstring = "";
XmlDocument xml = new XmlDocument ();
Xml. Load (path);
System.Xml.XmlElement root = Xml. DocumentElement;
System.Xml.XmlNode node = root. selectSingleNode ("//" + nodename);
if (node!= null)
{
xmlstring = node. InnerText;
}
return xmlstring;
}
#endregion
}
   }

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.