C # Operations XML summary (beginner)

Source: Internet
Author: User

First, Brief introduction

Using System.Xml;
Initializing an XML instance
XmlDocument xml=new XmlDocument ();

Import the specified XML file
Xml. Load (path);
Xml. Load (HttpContext.Current.Server.MapPath ("~/file/bookstore.xml"));

Specify a node
XmlNode Root=xml. selectSingleNode ("/root");

Get all immediate child nodes under a node
XmlNodeList Childlist=root. ChildNodes;

Determine if there are child nodes under the node
Root. HasChildNodes;

Gets a collection of sibling nodes with the same name
XmlNodeList Nodelist=xml. SelectNodes ("/root/news");

Generate a new node
XmlElement Node=xml. CreateElement ("News");

Adds a node to the specified node as its child node
Root. AppendChild (node);

Before adding a node to a child node under a specified node
Root. InsertBefore (Node,root. Childenodes[i]);

Creates a new property for the specified node and assigns a value
Node. SetAttribute ("id", "11111");

To add a child node to a specified node
Root. AppendChild (node);

Gets the specified property value for the specified node
String Id=node. attributes["id"]. Value;

Gets the text in the specified node
String Content=node. InnerText;

Save the XML file
String Path=server.mappath ("~/file/bookstore.xml");
Xml. Save (path);
or Use:xml. Save (HttpContext.Current.Server.MapPath ("~/file/bookstore.xml"));

Second, specific examples

How XML is manipulated in C#.net
Namespaces that need to be added:
Using System.Xml;

Define several common objects:
XmlDocument xmldoc;
XmlNode XmlNode;
XmlElement Xmlelem;

1, create an XML file to the server directory with the same name:


Method One:
xmldoc = new XmlDocument ();
Join the declaration paragraph of XML, <?xml version= "1.0" encoding= "gb2312"?>
XmlDeclaration xmldecl;
Xmldecl = xmldoc. Createxmldeclaration ("1.0", "gb2312", null);
XmlDoc. AppendChild (XMLDECL);

Add a root element
Xmlelem = xmldoc. CreateElement ("", "Employees", "");
XmlDoc. AppendChild (Xmlelem);
Add a different element
for (int i=1;i<3;i++)
{

XmlNode Root=xmldoc. selectSingleNode ("Employees");//Find <Employees>
XmlElement Xe1=xmldoc. CreateElement ("node");//Create a <Node> 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 beginner to proficient";//Set Text node
Xe1. AppendChild (XESUB1);//Add to <Node> node
XmlElement Xesub2=xmldoc. CreateElement ("author");
Xesub2. Innertext= "Waiting for the Czech Republic";
Xe1. AppendChild (XESUB2);
XmlElement Xesub3=xmldoc. CreateElement ("Price");
Xesub3. innertext= "58.3";
Xe1. AppendChild (XESUB3);

Root. AppendChild (XE1);//Add to <Employees> node
}
Save the created XML document
XmlDoc. Save (Server.MapPath ("Data.xml"));

//////////////////////////////////////////////////////////////////////////////////////
Result: A file named Data.xml was generated under the same name, with the following
<?xml version= "1.0" encoding= "gb2312"?>
<Employees>
<node genre= "Li Zhanhong" isbn= "2-3631-4" >
<title>cs from getting started to mastering </title>
<author> </author>
<price>58.3</price>
</Node>
<node genre= "Li Zhanhong" isbn= "2-3631-4" >
<title>cs from getting started to mastering </title>
<author> </author>
<price>58.3</price>
</Node>
</Employees>


Method Two:
XmlTextWriter XmlWriter;
String strFileName = Server.MapPath ("Data1.xml");

XmlWriter = new XmlTextWriter (strfilename,encoding.default);//Create an XML document
xmlwriter.formatting = formatting.indented;
Xmlwriter.writestartdocument ();
Xmlwriter.writestartelement ("Employees");

Xmlwriter.writestartelement ("Node");
Xmlwriter.writeattributestring ("Genre", "Li Zhanhong");
Xmlwriter.writeattributestring ("ISBN", "2-3631-4");

Xmlwriter.writestartelement ("title");
Xmlwriter.writestring ("CS from beginner to proficient");
Xmlwriter.writeendelement ();

Xmlwriter.writestartelement ("author");
Xmlwriter.writestring ("Waiting for the Czech Republic");
Xmlwriter.writeendelement ();

Xmlwriter.writestartelement ("Price");
Xmlwriter.writestring ("58.3");
Xmlwriter.writeendelement ();

Xmlwriter.writeendelement ();

Xmlwriter.close ();
//////////////////////////////////////////////////////////////////////////////////////
Results:
<?xml version= "1.0" encoding= "gb2312"?>
<Employees>
<node genre= "Li Zhanhong" isbn= "2-3631-4" >
<title>cs from getting started to mastering </title>
<author> </author>
<price>58.3</price>
</Node>
</Employees>

2, add a node:

XmlDocument xmldoc=new XmlDocument ();
Xmldoc.load (Server.MapPath ("Data.xml"));
XmlNode Root=xmldoc.selectsinglenode ("Employees");//Find <Employees>
XmlElement xe1=xmldoc.createelement ("node");//Create a <Node> node
Xe1. SetAttribute ("Genre", "Zhang San");//Set the node genre property
Xe1. SetAttribute ("ISBN", "1-1111-1");//Set the node ISBN property

XmlElement xesub1=xmldoc.createelement ("title");
Xesub1. Innertext= "C # Getting Started help";//Setting Up a text node
Xe1. AppendChild (XESUB1);//Add to <Node> node
XmlElement xesub2=xmldoc.createelement ("author");
Xesub2. innertext= "Master";
Xe1. AppendChild (XESUB2);
XmlElement xesub3=xmldoc.createelement ("price");
Xesub3. innertext= "158.3";
Xe1. AppendChild (XESUB3);

Root. AppendChild (XE1);//Add to <Employees> node
Xmldoc.save (Server.MapPath ("Data.xml"));

//////////////////////////////////////////////////////////////////////////////////////
Result: A node is added to the original XML content as follows,
<?xml version= "1.0" encoding= "gb2312"?>
<Employees>
<node genre= "Li Zhanhong" isbn= "2-3631-4" >
<title>cs from getting started to mastering </title>
<author> </author>
<price>58.3</price>
</Node>
<node genre= "Li Zhanhong" isbn= "2-3631-4" >
<title>cs from getting started to mastering </title>
<author> </author>
<price>58.3</price>
</Node>
<node genre= "Zhang San" isbn= "1-1111-1" >
<title>c# Getting Started help </title>
<author> Master </author>
<price>158.3</price>
</Node>
</Employees>

3, modify the value of the node (attributes and sub-nodes):

XmlDocument xmldoc=new XmlDocument ();
Xmldoc.load (Server.MapPath ("Data.xml"));

XmlNodeList Nodelist=xmldoc.selectsinglenode ("Employees"). childnodes;//get all child nodes of the Employees node

foreach (XmlNode xn in nodeList)//traverse all child nodes
{
XmlElement xe= (XmlElement) xn;//to convert child node types to XmlElement types
if (XE. GetAttribute ("genre") = = "Zhang San")//if the genre attribute value is "Zhang San"
{
Xe. SetAttribute ("Genre", "Update Zhang San");//Modify this property to "Update Zhang San"

XmlNodeList Nls=xe. childnodes;//continue to acquire 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= "Ya sheng";//Modify
}
}
}
}
Xmldoc.save (Server.MapPath ("Data.xml"));//save.

//////////////////////////////////////////////////////////////////////////////////////
Result: The information for all the previous nodes has been modified , the contents of the XML are as follows,
<?xml version= "1.0" encoding= "gb2312"?
<employees>
  <node genre= "Li Zhanhong" Isbn= "2-3631-4";
    <title>cs from getting started to mastering </title>
    <author > </author>
    <price>58.3</price>
  </node>
  <node genre= "Li Zhanhong" isbn= "2-3631-4";
    <title>cs from getting started to mastering </title>
     <author> </author>
    <price>58.3</price>
  < /node>
  <node genre= "update Zhang San" isbn= "1-1111-1";
    <title>c# Getting Started help </ Title>,
    <author> </author>
    <price>158.3</ Price>
  </node>
</employees>

4, modify the node (add the node's attributes and add the node's self-node):
XmlDocument xmldoc=new XmlDocument ();
Xmldoc.load (Server.MapPath ("Data.xml"));

XmlNodeList Nodelist=xmldoc.selectsinglenode ("Employees"). childnodes;//get all child nodes of the Employees node

foreach (XmlNode xn in nodeList)
{
XmlElement xe= (XmlElement) xn;
Xe. SetAttribute ("Test", "111111");

XmlElement xesub=xmldoc.createelement ("flag");
Xesub. innertext= "1";
Xe. AppendChild (xesub);
}
Xmldoc.save (Server.MapPath ("Data.xml"));

//////////////////////////////////////////////////////////////////////////////////////
Result: The attributes of each node are added with one, and the sub-nodes are also added, the contents are as follows,
<?xml version= "1.0" encoding= "gb2312"?>
<Employees>
<node genre= "Li Zhanhong" isbn= "2-3631-4" test= "111111" >
<title>cs from getting started to mastering </title>
<author> </author>
<price>58.3</price>
<flag>1</flag>
</Node>
<node genre= "Li Zhanhong" isbn= "2-3631-4" test= "111111" >
<title>cs from getting started to mastering </title>
<author> </author>
<price>58.3</price>
<flag>1</flag>
</Node>
<node genre= "Update Zhang San" isbn= "1-1111-1" test= "111111" >
<title>c# Getting Started help </title>
<author> ya sheng </author>
<price>158.3</price>
<flag>1</flag>
</Node>
</Employees>

5, delete one of the properties in the node:
XmlDocument xmldoc=new XmlDocument ();
Xmldoc.load (Server.MapPath ("Data.xml"));
XmlNodeList Xnl=xmldoc.selectsinglenode ("Employees"). ChildNodes;
foreach (XmlNode xn in xnl)
{
XmlElement xe= (XmlElement) xn;
Xe. RemoveAttribute ("genre");//Delete genre property

XmlNodeList Nls=xe. CHILDNODES;//continues to acquire all child nodes of the XE child node  
foreach (XmlNode xn1 in NLS)//traverse  

XmlElement xe2= ( XmlElement) xn1;//conversion type  
if (Xe2. name== "flag")//if   is found;

Xe. RemoveChild (XE2);//delete



Xmldoc.save (Server.MapPath ("Data.xml"));

//////////////////////////////////////////////////////////////////////////////////////]
Result: Delete A property of the endpoint and a sub-node of the node, as follows,
<?xml version= "1.0" encoding= "gb2312"?
<employees>
  <node isbn= "2-3631-4" test= "111111";
    <title>cs from getting started to mastering </title>
     <author> </author>
    <price>58.3</price>
  < /node>,
  <node isbn= "2-3631-4" test= "111111";
    <title>cs from getting started to mastering </ Title>,
    <author> </author>
    <price>58.3</ Price>
  </node>
  <node isbn= "1-1111-1" test= "111111";
    < title>c# starter Help </title>
    <author> </author>
    < Price>158.3</price>
  </node>
</employees>

6. Delete the node:
XmlDocument xmldoc=new XmlDocument ();
Xmldoc.load (Server.MapPath ("Data.xml"));
XmlNode Root=xmldoc.selectsinglenode ("Employees");
XmlNodeList Xnl=xmldoc.selectsinglenode ("Employees"). ChildNodes;
for (int i=0;i<xnl. count;i++)
{
XmlElement xe= (XmlElement) xnl. Item (i);
if (XE. GetAttribute ("genre") = = "Zhang San")
{
Root. RemoveChild (XE);
if (I<XNL. Count) i=i-1;
}
}
Xmldoc.save (Server.MapPath ("Data.xml"));

//////////////////////////////////////////////////////////////////////////////////////]
Result: Delete all the nodes that match the condition, the original content:

<?xml version= "1.0" encoding= "gb2312"?>
<Employees>
<node genre= "Li Zhanhong" isbn= "2-3631-4" >
<title>cs from getting started to mastering </title>
<author> </author>
<price>58.3</price>
</Node>
<node genre= "Li Zhanhong" isbn= "2-3631-4" >
<title>cs from getting started to mastering </title>
<author> </author>
<price>58.3</price>
</Node>
<node genre= "Zhang San" isbn= "1-1111-1" >
<title>c# Getting Started help </title>
<author> Master </author>
<price>158.3</price>
</Node>
<node genre= "Zhang San" isbn= "1-1111-1" >
<title>c# Getting Started help </title>
<author> Master </author>
<price>158.3</price>
</Node>
</Employees>

Content after deletion:
<?xml version= "1.0" encoding= "gb2312"?>
<Employees>
<node genre= "Li Zhanhong" isbn= "2-3631-4" >
<title>cs from getting started to mastering </title>
<author> </author>
<price>58.3</price>
</Node>
<node genre= "Li Zhanhong" isbn= "2-3631-4" >
<title>cs from getting started to mastering </title>
<author> </author>
<price>58.3</price>
</Node>
</Employees>

7, read the XML as a text file

System.IO.StreamReader MyFile =new
System.IO.StreamReader (Server.MapPath ("Data.xml"), System.Text.Encoding.Default);
Note System.Text.Encoding.Default

String myString = Myfile.readtoend ();//mystring is a read-out string
Myfile.close ();

third, advanced applications

/* Read XML data in two XML ways */
<aaa>
<bb>something</bb>
<cc>something</cc>
</aaa>

<aaa>
<add key= "123" value= "321"/>
</aaa>

/* First Method */
Ds. READXML ("Your xmlfile name");
Container.DataItem ("BB");
Container.DataItem ("CC");
Ds. ReadXmlSchema ("Your xmlfile name");

/* The second method */
<aaa>
<add key= "123" value= "321"/>
</aaa>
What should I do if I want to find 123 and then fetch 321?

Using System.Xml;
XmlDataDocument xmldoc = new System.Xml.XmlDataDocument ();
Xmldoc.load (@ "C:/config.xml");
XmlElement Elem = Xmldoc.getelementbyid ("add");
String str = Elem. attributes["Value"]. Value


/* Third method: selectSingleNode read XML in two formats *---/
--------------------------------------------------------------------
<?xml version= "1.0" encoding= "Utf-8"?>
<configuration>
<appSettings>
<connectionstring>data SOURCE=YF; User id=ctm_dbo;password=123</connectionstring>
</appSettings>
</configuration>
--------------------------------------------------------------------------
XmlDocument doc = new XmlDocument ();
Doc. Load (Strxmlname);

XmlNode Node=doc. selectSingleNode ("/configuration/appsettings/connectionstring");
if (node!=null)
{
String K1=node.    Value; Null
String K2=node. Innertext;//data SOURCE=YF; User id=ctm_dbo;password=123
String K3=node. Innerxml;//data SOURCE=YF; User id=ctm_dbo;password=123
Node=null;
}

********************************************************************
<?xml version= "1.0" encoding= "Utf-8"?>
<configuration>
<appSettings>
<add key= "ConnectionString" value= "Data source=yf; User id=ctm_dbo;password=123 "/>
</appSettings>
</configuration>
**--------------------------------------------------------------------**
XmlNode Node=doc. selectSingleNode ("/configuration/appsettings/add");
if (node!=null)
{
String K=node. attributes["Key"]. Value;
String V=node. attributes["Value"]. Value;
Node=null;
}
*--------------------------------------------------------------------*
XmlNode Node=doc. selectSingleNode ("/configuration/appsettings/add");
if (node!=null)
{
XmlNodeReader nr=new XmlNodeReader (node);
Nr. MoveToContent ();
Checks whether the current node is a content node. If this node is not a content node, the reader jumps forward to the next content node or end of the file.
Nr. MoveToAttribute ("value");
String S=nr. Value;
Node=null;
}

C # Operations XML summary (beginner)

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.