search
  • Sign In
  • Sign Up
Password reset successful

Follow the proiects vou are interested in andi aet the latestnews about them taster

Home Backend Development XML/RSS Tutorial XML add, delete, modify and query examples

XML add, delete, modify and query examples

Feb 27, 2017 pm 04:47 PM
xml Add, delete, modify and check

1.已知有一个XML文件(bookstore.xml)如下:

<?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、往<bookstore>节点中插入一个<book>节点:

   XmlDocument xmlDoc=new XmlDocument();
   xmlDoc.Load(&quot;bookstore.xml&quot;);
   XmlNode root=xmlDoc.SelectSingleNode(&quot;bookstore&quot;);//查找&lt;bookstore&gt;
   XmlElement xe1=xmlDoc.CreateElement(&quot;book&quot;);//创建一个&lt;book&gt;节点
   xe1.SetAttribute(&quot;genre&quot;,&quot;李赞红&quot;);//设置该节点genre属性
   xe1.SetAttribute(&quot;ISBN&quot;,&quot;2-3631-4&quot;);//设置该节点ISBN属性

   XmlElement xesub1=xmlDoc.CreateElement(&quot;title&quot;);
   xesub1.InnerText=&quot;CS从入门到精通&quot;;//设置文本节点
   xe1.AppendChild(xesub1);//添加到&lt;book&gt;节点中
   XmlElement xesub2=xmlDoc.CreateElement(&quot;author&quot;);
   xesub2.InnerText=&quot;候捷&quot;;
   xe1.AppendChild(xesub2);
   XmlElement xesub3=xmlDoc.CreateElement(&quot;price&quot;);
   xesub3.InnerText=&quot;58.3&quot;;
   xe1.AppendChild(xesub3);

   root.AppendChild(xe1);//添加到&lt;bookstore&gt;节点中
   xmlDoc.Save(&quot;bookstore.xml&quot;);

//================
结果为:

&lt;?xml version=&quot;1.0&quot; encoding=&quot;gb2312&quot;?&gt;
&lt;bookstore&gt;
  &lt;book genre=&quot;fantasy&quot; ISBN=&quot;2-3631-4&quot;&gt;
    &lt;title&gt;Oberon&#39;s Legacy&lt;/title&gt;
    &lt;author&gt;Corets, Eva&lt;/author&gt;
    &lt;price&gt;5.95&lt;/price&gt;
  &lt;/book&gt;
  &lt;book genre=&quot;李赞红&quot; ISBN=&quot;2-3631-4&quot;&gt;
    &lt;title&gt;CS从入门到精通&lt;/title&gt;
    &lt;author&gt;候捷&lt;/author&gt;
    &lt;price&gt;58.3&lt;/price&gt;
  &lt;/book&gt;
&lt;/bookstore&gt;

2、修改节点:将genre属性值为“李赞红“的节点的genre值改为“update李赞红”,将该节点的子节点<author>的文本修改为“亚胜”。

  XmlNodeList nodeList=xmlDoc.SelectSingleNode(&quot;bookstore&quot;).ChildNodes;//获取bookstore节点的所有子节点
   foreach(XmlNode xn in nodeList)//遍历所有子节点
   {
    XmlElement xe=(XmlElement)xn;//将子节点类型转换为XmlElement类型
    if(xe.GetAttribute(&quot;genre&quot;)==&quot;李赞红&quot;)//如果genre属性值为“李赞红”
    {
     xe.SetAttribute(&quot;genre&quot;,&quot;update李赞红&quot;);//则修改该属性为“update李赞红”

     XmlNodeList nls=xe.ChildNodes;//继续获取xe子节点的所有子节点
     foreach(XmlNode xn1 in nls)//遍历
     {
      XmlElement xe2=(XmlElement)xn1;//转换类型
      if(xe2.Name==&quot;author&quot;)//如果找到
      {
       xe2.InnerText=&quot;亚胜&quot;;//则修改
       break;//找到退出来就可以了
      }
     }
     break;
    }
   }

   xmlDoc.Save(&quot;bookstore.xml&quot;);//保存。

//=================

最后结果为:

&lt;?xml version=&quot;1.0&quot; encoding=&quot;gb2312&quot;?&gt;
&lt;bookstore&gt;
  &lt;book genre=&quot;fantasy&quot; ISBN=&quot;2-3631-4&quot;&gt;
    &lt;title&gt;Oberon&#39;s Legacy&lt;/title&gt;
    &lt;author&gt;Corets, Eva&lt;/author&gt;
    &lt;price&gt;5.95&lt;/price&gt;
  &lt;/book&gt;
  &lt;book genre=&quot;update李赞红&quot; ISBN=&quot;2-3631-4&quot;&gt;
    &lt;title&gt;CS从入门到精通&lt;/title&gt;
    &lt;author&gt;亚胜&lt;/author&gt;
    &lt;price&gt;58.3&lt;/price&gt;
  &lt;/book&gt;
&lt;/bookstore&gt;

3、删除 <book genre="fantasy" ISBN="2-3631-4">节点的genre属性,删除 <book genre="update李赞红" ISBN="2-3631-4">节点。

XmlNodeList xnl=xmlDoc.SelectSingleNode(&quot;bookstore&quot;).ChildNodes;

   foreach(XmlNode xn in xnl)
   {
    XmlElement xe=(XmlElement)xn;
    if(xe.GetAttribute(&quot;genre&quot;)==&quot;fantasy&quot;)
    {
     xe.RemoveAttribute(&quot;genre&quot;);//删除genre属性
    }
    else if(xe.GetAttribute(&quot;genre&quot;)==&quot;update李赞红&quot;)
    {
     xe.RemoveAll();//删除该节点的全部内容
    }
   }
   xmlDoc.Save(&quot;bookstore.xml&quot;);

//====================

最后结果为:

&lt;?xml version=&quot;1.0&quot; encoding=&quot;gb2312&quot;?&gt;
&lt;bookstore&gt;
  &lt;book ISBN=&quot;2-3631-4&quot;&gt;
    &lt;title&gt;Oberon&#39;s Legacy&lt;/title&gt;
    &lt;author&gt;Corets, Eva&lt;/author&gt;
    &lt;price&gt;5.95&lt;/price&gt;
  &lt;/book&gt;
  &lt;book&gt;
  &lt;/book&gt;
&lt;/bookstore&gt;

4、显示所有数据。

 XmlNode xn=xmlDoc.SelectSingleNode(&quot;bookstore&quot;);

   XmlNodeList xnl=xn.ChildNodes;

   foreach(XmlNode xnf in xnl)
   {
    XmlElement xe=(XmlElement)xnf;
    Console.WriteLine(xe.GetAttribute(&quot;genre&quot;));//显示属性值
    Console.WriteLine(xe.GetAttribute(&quot;ISBN&quot;));

    XmlNodeList xnf1=xe.ChildNodes;
    foreach(XmlNode xn2 in xnf1)
    {
     Console.WriteLine(xn2.InnerText);//显示子节点点文本
    }
   }

2前台代码:html

&lt;%@ Page language=&quot;c#&quot; Codebehind=&quot;Main.aspx.cs&quot; AutoEventWireup=&quot;false&quot; Inherits=&quot;DsAndXML.OpXMLFile.Main&quot; %&gt;
&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0 Transitional//EN&quot; &gt;
&lt;HTML&gt;
    &lt;HEAD&gt;
        &lt;title&gt;Main&lt;/title&gt;
        &lt;meta name=&quot;GENERATOR&quot; Content=&quot;Microsoft Visual Studio 7.0&quot;&gt;
        &lt;meta name=&quot;CODE_LANGUAGE&quot; Content=&quot;C#&quot;&gt;
        &lt;meta name=&quot;vs_defaultClientScript&quot; content=&quot;JavaScript&quot;&gt;
        &lt;meta name=&quot;vs_targetSchema&quot; content=&quot;http://schemas.microsoft.com/intellisense/ie5&quot;&gt;
    &lt;/HEAD&gt;
    &lt;body MS_POSITIONING=&quot;GridLayout&quot;&gt;
        &lt;form id=&quot;Main&quot; method=&quot;post&quot; runat=&quot;server&quot;&gt;
            &lt;FONT face=&quot;宋体&quot;&gt;
    &lt;asp:DataGrid id=&quot;dgShow&quot; style=&quot;Z-INDEX: 100; LEFT: 113px; POSITION: absolute; TOP: 32px&quot; runat=&quot;server&quot; Width=&quot;480px&quot; Height=&quot;178px&quot;&gt;&lt;/asp:DataGrid&gt;
    &lt;asp:Label id=&quot;Label3&quot; style=&quot;Z-INDEX: 111; LEFT: 187px; POSITION: absolute; TOP: 383px&quot; runat=&quot;server&quot; Width=&quot;120px&quot; Height=&quot;21px&quot;&gt;新邮件地址:&lt;/asp:Label&gt;
      &lt;asp:Label id=&quot;Label2&quot; style=&quot;Z-INDEX: 107; LEFT: 333px; POSITION: absolute; TOP: 274px&quot; runat=&quot;server&quot; Width=&quot;83px&quot; Height=&quot;21px&quot;&gt;邮件地址:&lt;/asp:Label&gt;
          &lt;asp:Button id=&quot;btnAdd&quot; style=&quot;Z-INDEX: 104; LEFT: 298px; POSITION: absolute; TOP: 324px&quot; runat=&quot;server&quot; Text=&quot;添加&quot;&gt;&lt;/asp:Button&gt;
                &lt;asp:Button id=&quot;btnDelete&quot; style=&quot;Z-INDEX: 103; LEFT: 199px; POSITION: absolute; TOP: 324px&quot; runat=&quot;server&quot; Text=&quot;删除&quot;&gt;&lt;/asp:Button&gt;
                &lt;asp:Button id=&quot;btnChange&quot; style=&quot;Z-INDEX: 102; LEFT: 102px; POSITION: absolute; TOP: 382px&quot; runat=&quot;server&quot; Text=&quot;修改&quot;&gt;&lt;/asp:Button&gt;
                &lt;asp:Button id=&quot;btnQuery&quot; style=&quot;Z-INDEX: 101; LEFT: 101px; POSITION: absolute; TOP: 324px&quot; runat=&quot;server&quot; Text=&quot;查询&quot;&gt;&lt;/asp:Button&gt;
 &lt;asp:DropDownList id=&quot;ddlName&quot; style=&quot;Z-INDEX: 105; LEFT: 210px; POSITION: absolute; TOP: 274px&quot; runat=&quot;server&quot; Width=&quot;95px&quot; Height=&quot;78px&quot;&gt;&lt;/asp:DropDownList&gt;
 &lt;asp:Label id=&quot;Label1&quot; style=&quot;Z-INDEX: 106; LEFT: 100px; POSITION: absolute; TOP: 274px&quot; runat=&quot;server&quot; Width=&quot;83px&quot; Height=&quot;21px&quot;&gt;姓名:&lt;/asp:Label&gt;
                &lt;asp:Label id=&quot;lbEmail&quot; style=&quot;Z-INDEX: 109; LEFT: 459px; POSITION: absolute; TOP: 274px&quot; runat=&quot;server&quot; Width=&quot;231px&quot;&gt;&lt;/asp:Label&gt;
 &lt;asp:TextBox id=&quot;tbNewMail&quot; style=&quot;Z-INDEX: 110; LEFT: 330px; POSITION: absolute; TOP: 381px&quot; runat=&quot;server&quot; Width=&quot;208px&quot; Height=&quot;26px&quot;&gt;&lt;/asp:TextBox&gt;&lt;/FONT&gt;
        &lt;/form&gt;
    &lt;/body&gt;
&lt;/HTML&gt;

XML文件dbGuest.xml

&lt;?xml version=&quot;1.0&quot; standalone=&quot;yes&quot;?&gt;
&lt;dbGuest&gt;
  &lt;User&gt;
    &lt;Name&gt;aaa&lt;/Name&gt;
    &lt;City&gt;shanghai&lt;/City&gt;
    &lt;Email&gt;aaa@263.net&lt;/Email&gt;
    &lt;Message&gt;ok&lt;/Message&gt;
    &lt;STime&gt;2004-07-12T00:00:00.0000000+08:00&lt;/STime&gt;
  &lt;/User&gt;
  &lt;User&gt;
    &lt;Name&gt;shaoazhd&lt;/Name&gt;
    &lt;City&gt;beijing&lt;/City&gt;
    &lt;Email&gt;sss@22.net&lt;/Email&gt;
    &lt;Message&gt;afsa&lt;/Message&gt;
    &lt;STime&gt;2004-7-12 15:07:39&lt;/STime&gt;
  &lt;/User&gt;
  &lt;User&gt;
    &lt;Name&gt;Guset&lt;/Name&gt;
    &lt;City&gt;上海&lt;/City&gt;
    &lt;Email&gt;sfaf@22.net&lt;/Email&gt;
  &lt;/User&gt;
  &lt;User&gt;
    &lt;Name&gt;Guset&lt;/Name&gt;
    &lt;City&gt;上海&lt;/City&gt;
    &lt;Email&gt;ss@22.net&lt;/Email&gt;
  &lt;/User&gt;
&lt;/dbGuest&gt;
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Xml;
using System.Xml.XPath;
namespace DsAndXML.OpXMLFile
{
    /// &lt;summary&gt;
    /// Main 的摘要说明。
    /// &lt;/summary&gt;
    public class Main : System.Web.UI.Page
    {
        protected System.Web.UI.WebControls.Button btnQuery;
        protected System.Web.UI.WebControls.Button btnChange;
        protected System.Web.UI.WebControls.Button btnDelete;
        protected System.Web.UI.WebControls.Button btnAdd;
        protected System.Web.UI.WebControls.DropDownList ddlName;
        protected System.Web.UI.WebControls.Label Label1;
        protected System.Web.UI.WebControls.Label Label2;
        protected System.Web.UI.WebControls.Label lbEmail;
        protected System.Web.UI.WebControls.TextBox tbNewMail;
        protected System.Web.UI.WebControls.Label Label3;
        protected System.Web.UI.WebControls.DataGrid dgShow;
    
        private void Page_Load(object sender, System.EventArgs e)
        {
            // 在此处放置用户代码以初始化页面
            if(!IsPostBack)
            Bind();

        }
        private void Bind()
        {
            DataSet ds = new DataSet();
            ds.ReadXml(Server.MapPath(&quot;.\\db\\dbGuest.xml&quot;));
            dgShow.DataSource = ds.Tables[0].DefaultView;
            dgShow.DataBind();
            XmlDocument doc = new XmlDocument();
            doc.Load(Server.MapPath(&quot;.\\db\\dbGuest.xml&quot;));
            XmlNodeList elemList = doc.GetElementsByTagName(&quot;Name&quot;);
            ddlName.Items.Clear();
            for(int i=0;i&lt;elemList.Count;i++)
             ddlName.Items.Add(elemList[i].InnerXml);
            
        }

        Web Form Designer generated code

        private void btnQuery_Click(object sender, System.EventArgs e)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(Server.MapPath(&quot;.\\db\\dbGuest.xml&quot;));
            lbEmail.Text = doc.SelectSingleNode(&quot;//User[Name=&#39;&quot;+ddlName.SelectedItem.Text+&quot;&#39;]&quot;).ChildNodes.Item(2).InnerText;
         
        }

        private void btnChange_Click(object sender, System.EventArgs e)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(Server.MapPath(&quot;.\\db\\dbGuest.xml&quot;));
            XmlNodeList nodeList=xmlDoc.SelectSingleNode(&quot;dbGuest&quot;).ChildNodes;//获取dbGuest节点的所有子节点
            foreach(XmlNode xn in nodeList)//遍历所有子节点
            {
                XmlElement xe=(XmlElement)xn;//将子节点类型转换为XmlElement类型
            
                XmlNodeList node = xe.GetElementsByTagName(&quot;Name&quot;);
                if(node.Count&gt;0)
                {

                    if(node[0].InnerText==ddlName.SelectedItem.Text)
                    {
                        XmlNodeList nls=xe.ChildNodes;//继续获取xe子节点的所有子节点
                        foreach(XmlNode xn1 in nls)//遍历
                        {
                            XmlElement xe2=(XmlElement)xn1;//转换类型
                            if(xe2.Name==&quot;Email&quot;)//如果找到
                            {
                                xe2.InnerText=tbNewMail.Text;//则修改
                                break;//找到退出来就可以了
                            }
                        }
                        break;
                    }
                }
                
            }
            xmlDoc.Save(Server.MapPath(&quot;.\\db\\dbGuest.xml&quot;));
            Bind();
        }

        private void btnDelete_Click(object sender, System.EventArgs e)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(Server.MapPath(&quot;.\\db\\dbGuest.xml&quot;));
            XmlNodeList xnl=xmlDoc.SelectSingleNode(&quot;dbGuest&quot;).ChildNodes;
 
            foreach(XmlNode xn in xnl)
            {
                XmlElement xe=(XmlElement)xn;
                XmlNodeList node = xe.GetElementsByTagName(&quot;Name&quot;);
                if(node.Count&gt;0)
                {

                    if(node[0].InnerText==ddlName.SelectedItem.Text)
                        xe.RemoveAll();//删除该节点的全部内容
                    break;
                }
            }
            
            xmlDoc.Save(Server.MapPath(&quot;.\\db\\dbGuest.xml&quot;));
            Bind();
        }

        private void btnAdd_Click(object sender, System.EventArgs e)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(Server.MapPath(&quot;.\\db\\dbGuest.xml&quot;));
            XmlNode root=xmlDoc.SelectSingleNode(&quot;dbGuest&quot;);//查找&lt;dbGuest&gt;
            XmlElement xe1=xmlDoc.CreateElement(&quot;User&quot;);//创建一个&lt;User&gt;节点
            XmlElement xesub1=xmlDoc.CreateElement(&quot;Name&quot;);
            xesub1.InnerText=&quot;Guset&quot;;//设置文本节点
            xe1.AppendChild(xesub1);//添加到&lt;User&gt;节点中
            XmlElement xesub2=xmlDoc.CreateElement(&quot;City&quot;);
            xesub2.InnerText=&quot;上海&quot;;
            xe1.AppendChild(xesub2);
            XmlElement xesub3=xmlDoc.CreateElement(&quot;Email&quot;);
            xesub3.InnerText=&quot;ss@22.net&quot;;
            xe1.AppendChild(xesub3);
 
            root.AppendChild(xe1);//添加到&lt;dbGuest&gt;节点中
            xmlDoc.Save(Server.MapPath(&quot;.\\db\\dbGuest.xml&quot;));
            Bind();
        }
    }
}

 以上就是XML 增、删、改和查示例的内容,更多相关内容请关注PHP中文网(m.sbmmt.com)!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Popular tool

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

JSON vs. XML: Why RSS Chose XML JSON vs. XML: Why RSS Chose XML May 05, 2025 am 12:01 AM

RSS chose XML instead of JSON because: 1) XML's structure and verification capabilities are better than JSON, which is suitable for the needs of RSS complex data structures; 2) XML was supported extensively at that time; 3) Early versions of RSS were based on XML and have become a standard.

Understanding RSS Documents: A Comprehensive Guide Understanding RSS Documents: A Comprehensive Guide May 09, 2025 am 12:15 AM

RSS documents are a simple subscription mechanism to publish content updates through XML files. 1. The RSS document structure consists of and elements and contains multiple elements. 2. Use RSS readers to subscribe to the channel and extract information by parsing XML. 3. Advanced usage includes filtering and sorting using the feedparser library. 4. Common errors include XML parsing and encoding issues. XML format and encoding need to be verified during debugging. 5. Performance optimization suggestions include cache RSS documents and asynchronous parsing.

Building XML Applications with C  : Practical Examples Building XML Applications with C : Practical Examples May 03, 2025 am 12:16 AM

You can use the TinyXML, Pugixml, or libxml2 libraries to process XML data in C. 1) Parse XML files: Use DOM or SAX methods, DOM is suitable for small files, and SAX is suitable for large files. 2) Generate XML file: convert the data structure into XML format and write to the file. Through these steps, XML data can be effectively managed and manipulated.

RSS, XML and the Modern Web: A Content Syndication Deep Dive RSS, XML and the Modern Web: A Content Syndication Deep Dive May 08, 2025 am 12:14 AM

RSS and XML are still important in the modern web. 1.RSS is used to publish and distribute content, and users can subscribe and get updates through the RSS reader. 2. XML is a markup language and supports data storage and exchange, and RSS files are based on XML.

XML in C  : Handling Complex Data Structures XML in C : Handling Complex Data Structures May 02, 2025 am 12:04 AM

Working with XML data structures in C can use the TinyXML or pugixml library. 1) Use the pugixml library to parse and generate XML files. 2) Handle complex nested XML elements, such as book information. 3) Optimize XML processing code, and it is recommended to use efficient libraries and streaming parsing. Through these steps, XML data can be processed efficiently.

Beyond Basics: Advanced RSS Features Enabled by XML Beyond Basics: Advanced RSS Features Enabled by XML May 07, 2025 am 12:12 AM

RSS enables multimedia content embedding, conditional subscription, and performance and security optimization. 1) Embed multimedia content such as audio and video through tags. 2) Use XML namespace to implement conditional subscriptions, allowing subscribers to filter content based on specific conditions. 3) Optimize the performance and security of RSSFeed through CDATA section and XMLSchema to ensure stability and compliance with standards.

Understanding RSS: An XML Perspective Understanding RSS: An XML Perspective Apr 25, 2025 am 12:14 AM

RSS is an XML-based format used to publish frequently updated content. 1. RSSfeed organizes information through XML structure, including title, link, description, etc. 2. Creating RSSfeed requires writing in XML structure, adding metadata such as language and release date. 3. Advanced usage can include multimedia files and classified information. 4. Use XML verification tools during debugging to ensure that the required elements exist and are encoded correctly. 5. Optimizing RSSfeed can be achieved by paging, caching and keeping the structure simple. By understanding and applying this knowledge, content can be effectively managed and distributed.

Inside the RSS Document: Essential XML Tags and Attributes Inside the RSS Document: Essential XML Tags and Attributes May 03, 2025 am 12:12 AM

The core structure of RSS documents includes XML tags and attributes. The specific parsing and generation steps are as follows: 1. Read XML files, process and tags. 2. Extract,,, etc. tag information. 3. Handle custom tags and attributes to ensure version compatibility. 4. Use cache and asynchronous processing to optimize performance to ensure code readability.

Related articles