asp.net C # Create modifications to XML documents delete lookup __.net

Source: Internet
Author: User

1. Create XML

To import namespaces:


Using System.Xml;

Create XML Object

xmldocument  xmldocument = new XmlDocument ();

Declares XML

 xmldeclaration xmldeclare =xmldocument.createxmldeclaration ("1.0", "Utf-8", null);

Create the root node

xmlelement elementroot =xmldocument.createelement ("Nodes");

Xmldocument.appendchild (elementroot);  

Create node Day

xmlelement elementday = xmldocument.createelement (' Day ');

       Set attributes to Node day and assign

Elementday.setattribute ("date", "Today"); 

Elementroot.appendchild (elementday);


Creates the child node part

XmlElement elementpart = xmldocument.createelement ("part") of day;

Elementpart.innertext = "AAA";

 Elementday.appendchild (Elementpart);

Save to XML file under

xmldocument.save ("./myxml.xml");


XML Generation data:

<Notes>

<day date= "Today" >

<part>aaa</part>

</Day>

</Notes>

2. Read and write XML files

<?xml version= "1.0" encoding= "Utf-8"?> <PhoneBook> <phone id= "001" > <Name> Garfield </Name> <Number>5555555</Number> <City> New York </City> <dateofbirth>26/10/1978</dateofbirth > </phone> <phone id= "002" > <Name> mike </Name> <Number>6666666</Number> <ci Ty> New York </City> <DateOfBirth>12/02/1978</DateOfBirth> </phone> </PhoneBook> ******** • Read and write XML methods using document private void Xmlfun () {Xmldo
   Cument doc = new XmlDocument (); Doc.

   Load (Server.MapPath ("Phone.xml")); XmlElement node = doc.
   createelement ("Phone"); XmlAttribute ATR = doc.
   CreateAttribute ("id"); Atr.
   innertext = "003"; Node.

   Attributes.append (ATR); XmlNode xnode = (XmlNode) doc.
   CreateElement ("Name"); XNode.
   innertext= "TestName"; Node.

   AppendChild (XNode); XNode = (XmlNode) doc.
   CreateElement ("number"); XNode.
   innertext= "119"; Node.
   AppendChild (XNode); XNode = (XmlNode) doc.
   CreateElement ("City"); XNode.
   Innertext= "CS"; Node.
   AppendChild (XNode); XNode = (XmlNode) doc.
   CreateElement ("dateOfBirth"); XNode.
   innertext= "12/02/1978"; Node.
   AppendChild (XNode); Doc. Documentelement.insertafter (Node,doc.

   Documentelement.lastchild); Doc.   Save (Server.MapPath ("Phone1.xml"));

 

 Must be saved as a different file}



• Write XML methods using XmlTextWriter

  private void XmlWriter ()
  {
   XmlTextWriter writer= new XmlTextWriter (Server.MapPath ("Phone4.xml"), null);
   Writer. formatting = formatting.indented;  Indent format
   writer. Indentation =4;

   Writer. WriteStartDocument ();

   Writer. WriteStartElement ("person");

   Writer. WriteStartAttribute ("ID", null);
   Writer. WriteString ("004");
   Writer. WriteEndAttribute ();

   Writer. WriteStartElement ("Name");
   Writer. WriteString ("Testwritername");
   Writer. WriteEndElement ();

   Writer. WriteStartElement ("number");
   Writer. WriteString ("88888");
   Writer. WriteEndElement ();

   Writer. WriteStartElement ("City");
   Writer. WriteString ("testwritercity");
   Writer. WriteEndElement ();

   Writer. Flush ();
   Writer. Close ();

  }

 


• Read XML methods using XmlTextReader

  private void Xmlread ()
  {
      XmlTextReader reader = new XmlTextReader (Server.MapPath ("Phone.xml"));
      while (reader. Read ())
      {
          if (reader). Localname.equals ("Name") | | Reader. Localname.equals ("number"))
      {this
      . Label1.Text + = reader. ReadString () + "T";
  }


 


• function Sqlcommand.executexmlreader () get XML

Sqlconnecting conn = new SqlConnection (CONNSTR);
SqlCommand cmd = new SqlCommand ("Select fname from Employee FOR XML Auto", conn);
Conn.Open ();
XmlReader reader = cmd. ExecuteXmlReader ();
......
################ XML Data Format #################

<employee fname= "aria"/> <employee
"Fname=" /> .....


3. Find XML

<Placemark>
<description>front line</description>
<Name>sole</Name>
<styleUrl> #roadStyle </styleUrl>
<LineString>
<coordinates>
114.0456,22.324
</coordinates>
</LineString>
</Placemark>
How to find this placemark based on the value of name
Let's insert the data into the
The coordinates node.

XmlElement chid_elent = doc.documentelement; Gets the root node of the XML
 if (Chid_Elent.ChildNodes.Count > 0)//If there is a child node under the root node
  {
       foreach (XmlElement elent in Chid_ Elent.childnodes)//loop Gets the node value
       {value=elent.innertext;//Gets the
             value
             elent.innertext=vaue;/or Assignment  Value is external variable
       }
}


Last Save (path)


4. Display all data

 

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
}
}


Finally, attach a C # operation XML Generic tool class

Using System;

Using System.Xml; namespace WLerp.Common.Util {///<summary>///Xml Operations Tool class///</summary> public sealed class X
        Mlutil {private Xmlutil () {}///<summary>///create node///</summary> <param name= "Node" ></param>///<param name= "Newelementname" ></param>/// 
            <returns></returns> public static XmlNode Appendelement (XmlNode node, string newelementname) {
        Return appendelement (node, newelementname, NULL); ///<summary>///Create node///</summary>///<param name= "Node" ></par am>///<param name= "Newelementname" ></param>///<param name= "Innervalue" ></param >///<returns></returns> public static XmlNode Appendelement (XmlNode node, string neweleme
     Ntname, String innervalue) {       XmlNode Onode; If (node is XmlDocument) {onode = node. AppendChild ((XmlDocument) node).
            CreateElement (Newelementname)); else {onode = node. AppendChild (node.
            Ownerdocument.createelement (Newelementname)); } if (Innervalue!= null) {onode.appendchild node.
            Ownerdocument.createtextnode (Innervalue));
        return onode; ///<summary>///Create properties///</summary>///<param name= "XmlDocument" >&
        lt;/param>///<param name= "name" ></param>///<param name= "value" ></param> <returns></returns> public static XmlAttribute CreateAttribute (XmlDocument XmlDocument, Strin
            G name, String value) {XmlAttribute Oatt = Xmldocument.createattribute (name);
     Oatt.value = Value;       return Oatt; ///<summary>///Set the value of the property///</summary>///<param name= "Node" ></p aram>///<param name= "AttributeName" ></param>///<param name= "AttributeValue" ></
            param> public static void SetAttribute (XmlNode node, string attributename, String attributevalue) { if (node. Attributes[attributename]!= null) {node. Attributes[attributename].
            Value = AttributeValue; } else {node. Attributes.append (node. CreateAttribute.
            Ownerdocument, AttributeName, AttributeValue)); }///<summary>///Gets the value of the property///</summary>///<param name= "Node" ></param>///<param name= "AttributeName" ></param>///<param name= "DefaultValue" & Gt;</param>///&LT;RETURNS&GT;&LT;/RETURNS&GT public static string GetAttribute (XmlNode node, string attributename, String defaultvalue) {Xmlattrib Ute ATT = node.
            Attributes[attributename]; if (att!= null) {return att.
            Value;
            else {return defaultvalue; }///<summary>///Gets the value of the node///</summary>///<param name= "Paren Tnode "></param>///<param name=" Nodexpath "></param>///<param name=" DefaultValue "></param>///<returns></returns> public static string Getnodevalue (XmlNode Parentno
            De, String Nodexpath, String defaultvalue) {XmlNode node = Parentnode.selectsinglenode (Nodexpath); if (node. FirstChild!= null) {return node.
            Firstchild.value;
    else if (node!= null) {            Return node.
            Value;
            else {return defaultvalue;
 }
        }
    }
}


reading XML node property values and node values

protected void Readnode_click (object sender, EventArgs e)
        {
            XmlDocument doc = new XmlDocument ();
            Doc. Load (Server.MapPath ("Student1.xml"));   
        
            XmlNodeList list = doc. getElementsByTagName ("Stuname"); Student1.xml files inside the stuname node
            foreach (XmlElement host in list)
            {
                Response.Write (" The value of the Name property of the Stuname node in the Student1.xml node is: "+ host." attributes["Name"]. Value + "<br/>");
                Response.Write (the value of the id attribute of the Stuname node in the Student1.xml node is: "+ host.) attributes["id"]. Value + "<br/>");             
            }


            String D1 = doc. selectSingleNode ("//stuname[@id = ' 1 ']/@name"). value;//reads the value of the name of ID 1 in the stuname tag
            Response.Write ("The value of the Name property of the Stuname node in the Student1.xml node is:" + D1 + "<br/>" );

 
        }


 protected void ReadXml () {XmlDocument xmldoc = new XmlDocument (); Xmldoc.load (Server.MapPath ("Student1.xml")); Load XML XmlNodeList nodelist = Xmldoc.selectnodes ("/students/student"); Path//Loop traversal node for XML node for (int i = 0; i < Nodelist.count i++) {Stri ng xmlstuname = nodelist[i]. Childnodes[0].    InnerText; Gets the Stuname string xmlstusex = Nodelist[i] of the first student node. CHILDNODES[1].     InnerText; Gets the Stusex string xmlstuage = Nodelist[i] of the first student node. CHILDNODES[2].     InnerText; Gets the Stuage string xmlstuaddress = Nodelist[i] of the first student node. CHILDNODES[3]. InnerText; Gets the stuaddress//loop of the first student node to read the XML node Information Response.Write ("node Stuname in the current XML file is:" + Xmlstun Ame + "<br/>" + "node in current XML file Stusex is:" + xmlstusex + "<br/>" + "node in current XML file Stuage is:" + xmlstuage + "<br /> "+" the node in the current XML file stuaddress is: "+ xmlstuaddRESS);
 }
        }

student1.xml file Contents:

<?xml version= "1.0" encoding= "Utf-8"?>
<Students>
  <Student>
    <stuname id= ' 1 ' name= ' Lizong ' >lili</StuName>
    <StuSex>nan</StuSex>
    <StuAge>24</StuAge>
    <StuAddress>shenzhen</StuAddress>
  </Student>
</Students>




Display the contents of the XML file through the GridView

 

 private void Loadgridview ()
        {

            DataSet ds = new DataSet ();
            Ds. READXML (Server.MapPath ("Xmltodataset.xml"));

            This. Gridview2.datasource = ds;
            This. Gridview2.databind ();
        }



xmltodataset.xml file Contents:

<?xml version= "1.0" encoding= "Utf-8"?>
<students>
  <student>
    <id>4</id>
    <name id= ' 1 ' name= ' Zhangsan ' >text4</name>
    <age>21</age>
  </student>
  <student>
    <id>5</id>
    <name id= ' 1 ' name= ' Zhangsan ' >text5</name>
    <age>22</age>
    <sex>nan</sex>
  </student>
  <student>
    < id>1</id>
    <name id= ' 1 ' name= ' Zhangsan ' >text1</name>
    <age>18</age>
  </student>
  <student>
    <id>2</id>
    <name id= ' 1 ' name= ' Zhangsan ' > text2</name>
    <age>19</age>
  </student>
  <student>
    <id>3 </id>
    <name id= ' 1 ' name= ' Zhangsan ' >text3</name>
    <age>20</age>
  </ Student>
</students>


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.