In C #, how does one modify, add, delete, and insert XML files?

Source: Internet
Author: User
In C #, how does one modify, add, delete, and insert XML files?

It is known that there is an XML file (bookstore. XML) as follows:
<? XML version = "1.0" encoding = "gb2312"?>
<Bookstore>
<Book genre = "Fantasy" ISBN = "2-3631-4">
<Title> Oberon's legacy </title>
<Author> corets, Eva </author>
<Price> 5.95 </price>
</Book>
</Bookstore>

1. Insert a <book> node to the <bookstore> node:

Xmldocument xmldoc = new xmldocument ();
Xmldoc. Load ("Bookstore. xml ");
Xmlnode root = xmldoc. selectsinglenode ("Bookstore"); // query <bookstore>
Xmlelement xe1 = xmldoc. createelement ("book"); // create a <book> 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 it to the <book> 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 it to the <bookstore> node
Xmldoc. Save ("Bookstore. xml ");

// ==========================
Result:

<? XML version = "1.0" encoding = "gb2312"?>
<Bookstore>
<Book genre = "Fantasy" ISBN = "2-3631-4">
<Title> Oberon's legacy </title>
<Author> corets, Eva </author>
<Price> 5.95 </price>
</Book>
<Book genre = "Li zanhong" ISBN = "2-3631-4">
<Title> Cs from entry to entry </title>
<Author> Hou Jie </author>
<Price> 58.3 </price>
</Book>
</Bookstore>

 

2. Modify the node: Change the genre value of the node whose genre attribute value is "Li zenhong" to "Update Li zenhong ", modify the text of the child node <author> of the node to "Yasheng ".

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:

<? XML version = "1.0" encoding = "gb2312"?>
<Bookstore>
<Book genre = "Fantasy" ISBN = "2-3631-4">
<Title> Oberon's legacy </title>
<Author> corets, Eva </author>
<Price> 5.95 </price>
</Book>
<Book genre = "Update Li zanhong" ISBN = "2-3631-4">
<Title> Cs from entry to entry </title>
<Author> Yasheng </author>
<Price> 58.3 </price>
</Book>
</Bookstore>

 

3. Delete the genre attribute of the <book genre = "Fantasy" ISBN = "2-3631-4"> node, delete the <book genre = "Update lizan red" ISBN = "2-3631-4"> node.

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:

<? XML version = "1.0" encoding = "gb2312"?>
<Bookstore>
<Book ISBN = "2-3631-4">
<Title> Oberon's legacy </title>
<Author> corets, Eva </author>
<Price> 5.95 </price>
</Book>
<Book>
</Book>
</Bookstore>

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

In addition:
Using system;
Using system. IO;
Using system. Web;
Using system. text;
Using system. xml;
Using system. collections;

 
Namespace shopweb. Class
{
/// <Summary>
/// Log summary.
/// </Summary>
Public class log
{
Private xmldocument xmllog = new xmldocument ();
Private httpcontext context = httpcontext. Current;
Private string xmlpath = "";
/// <Summary>
/// Constructor
/// </Summary>
/// <Param name = "xmlpath"> </param>
Public log (string xmlpath)
{

Xmlpath = xmlpath;
Xmllog. Load (context. server. mappath (xmlpath ));
}
/// <Summary>
/// Add a node that consists of subnodes
/// </Summary>
/// <Param name = "htchilds"> </param>
/// <Param name = "parentname"> </param>
/// <Returns> </returns>
Public bool addnodebychild (hashtable htchilds, string parentname)
{
Try
{

Xmlnode parent = xmllog. createelement (parentname );
Xmlnode child;
Idictionaryenumerator myenumerator = htchilds. getenumerator ();

While (myenumerator. movenext ())
{
Child = xmllog. createelement (myenumerator. Key. tostring ());
Child. innertext = myenumerator. value. tostring ();
Parent. appendchild (child );
Xmllog. documentelement. appendchild (parent );

}
Xmllog. Save (context. server. mappath (xmlpath ));
Return true;
}
Catch
{
Return false;

}

}
/// <Summary>
/// Add a node. The Node consists of attributes.
/// </Summary>
/// <Param name = "htattributes"> </param>
/// <Param name = "nodename"> </param>
/// <Returns> </returns>
Public bool addnodebyattribute (hashtable htattributes, string nodename)
{
Try
{
Xmlnode addnode = xmllog. createelement (nodename );
Idictionaryenumerator myenumerator = htattributes. getenumerator ();
Xmlattribute recognition;
While (myenumerator. movenext ())
{
Recognition = xmllog. createattribute (myenumerator. Key. tostring ());
Recognition. innertext = myenumerator. value. tostring ();
Addnode. Attributes. append (ASD );
Xmllog. documentelement. appendchild (addnode );

}
Xmllog. Save (context. server. mappath (xmlpath ));
Return true;
}
Catch
{
Return false;

}

}
/// <Summary>
/// Or specify the number of subnodes to be queried.
/// </Summary>
/// <Param name = "querypath"> </param>
/// <Returns> </returns>
Public int childcount (string querypath)
{
Try
{
Xmlnode resultnodes = xmllog. selectsinglenode (querypath );
Return resultnodes. childnodes. count;

}
Catch
{
Return-1;

}

}
/// <Summary>
/// Delete the node in the specified path
/// </Summary>
/// <Param name = "querypath"> </param>
/// <Returns> </returns>
Public bool deleltenode (string querypath)
{
Try
{
Xmlnodelist resultnodes = xmllog. selectnodes (querypath );
For (INT I = 0; I <resultnodes. Count; I ++)
{
Xmlnode parentnode = resultnodes [I]. parentnode;
Parentnode. removechild (resultnodes [I]);

}
Xmllog. Save (context. server. mappath (xmlpath ));
Return true;

}
Catch
{
Return false;
}

}
/// <Summary>
/// Query a node
/// </Summary>
/// <Param name = "querypath"> </param>
/// <Returns> </returns>
Public xmlnodelist querynode (string querypath)
{
Try
{
Xmlnodelist resultnodes = xmllog. selectnodes (querypath );
Return resultnodes;
}
Catch
{
Return NULL;
}

}
}
}

Trackback: http://tb.blog.csdn.net/TrackBack.aspx? Postid = 118833

From: http://blog.csdn.net/xiaowu703/archive/2004/09/27/118833.aspx

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.