Home Backend Development XML/RSS Tutorial Personal summary of reading and writing all xml nodes and data summary of reading xml nodes

Personal summary of reading and writing all xml nodes and data summary of reading xml nodes

Feb 27, 2017 pm 05:03 PM

Read:

 //打开某文件(假设web.config在根目录中)
    string filename=Server.MapPath("/") + @"Webapplication1\web.config";
    xmlDocument xmldoc= new XmlDocument();
    xmldoc.Load(filename);
 
    //得到顶层节点列表
    XmlNodeList topM=xmldoc.DocumentElement.ChildNodes;
    foreach(XmlElement element in topM)
    {
     if(element.Name.ToLower()=="appsettings")
     {
 
      //得到该节点的子节点
      XmlNodeList nodelist=element.ChildNodes;
 
      if ( nodelist.Count >0 )
      {
       //DropDownList1.Items.Clear();
 
       foreach(XmlElement el in nodelist)//读元素值
       {
        //DropDownList1.Items.Add(el.Attributes["key"].InnerXml);
        //this.TextBox2.Text=el.Attributes["key"].InnerText;
        this.TextBox2.Text=el.Attributes["key"].Value;
        this.Label1.Text=el.Attributes["value"].Value;
 
 
            //同样在这里可以修改元素值,在后面save。
         //  el.Attributes["value"].Value=this.TextBox2.Text;
       }
 
      }
     }
    }
Copy after login

xmldoc.Save(filename);

Add an element under a node and set the value:

 if(element.Name.ToLower()=="appsettings")
    {
 
     XmlElement elem =xmldoc.CreateElement("add");
     
     element.AppendChild(elem);
     elem.InnerText="ltp";
 
     xmldoc.Save(filename);
       
    }
Copy after login

Effect:

<appSettings>
    <add key="密码" value="admin" />
    <add>ltp</add>
  </appSettings>
Copy after login

Add an element under a certain node and add two attributes:

 if(element.Name.ToLower()=="appsettings")
    {
 
     XmlElement elem =xmldoc.CreateElement("add");
     element.AppendChild(elem);
 
     XmlAttribute xa=xmldoc.CreateAttribute("key");
     xa.Value="ltp";
 
     XmlAttribute xa2=xmldoc.CreateAttribute("value");
     xa2.Value="first";
 
     elem.SetAttributeNode(xa);
     elem.SetAttributeNode(xa2);
 
     xmldoc.Save(filename);
       
    }
Copy after login

Effect:

  <appSettings>
    <add key="密码" value="admin" />
    <add key="ltp" value="first" />
  </appSettings>
 
//添加空元素:
   XmlNode node=doc.CreateElement(groupname);
     node.InnerText="";
     doc.LastChild.AppendChild(node);
 
     doc.Save(xmlfile);
Copy after login

Delete a node element

string itemname=this.listBox1.SelectedItem.ToString();
   
   this.listBox1.Items.Remove(this.listBox1.SelectedItem);
 
   //begin del xmlfile
   XmlDocument doc=new XmlDocument();
   doc.Load(xmlfile);
   
   XmlNodeList topM=doc.DocumentElement.ChildNodes;
   foreach(XmlElement element in topM)
   {
    if(element.Name==this.comboBox1.Text)
    {
 
     //得到该节点的子节点
     XmlNodeList nodelist=element.ChildNodes;      
 
     foreach(XmlElement el in nodelist)//读元素值
     {       
      if(el.Attributes["key"].Value==itemname)
      {
       element.RemoveChild(el);
      }
 
     }//循环元素
      
    }//得到组
 
   }//循环组
   doc.Save(xmlfile);  //一定要保存一下,否则不起作用
 
//筛选数据
PRivate void Reader_Xml(string pathFlie)
{
   XmlDocument Xmldoc=new XmlDocument();
   Xmldoc.Load(pathFlie);
   XmlNodeList Record1=Xmldoc.DocumentElement.SelectNodes(Code[@id=&#39;1&#39;])
   int f=0;
   foreach(XmlNode xnode in Record1)
    {
 
    }
} /**//*读取xml数据   两种xml方式*/
<aaa>
     <bb>something</bb>
     <cc>something</cc>
</aaa>
 
<aaa>
    <add key="123" value="321"/>
</aaa>
/**//*第一种方法*/
DS.ReadXml("your xmlfile name");
Container.DataItem("bb");
Container.DataItem("cc");
DS.ReadXmlSchema("your xmlfile name");
 
/**//*第二种方法*/
<aaa>
    <add key="123" value="321"/>
</aaa>
Copy after login

If I want to find 123 then How should I write when I get 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
 
 
/**//*第三种方法:  SelectSingleNode  读取两种格式的xml *---/
--------------------------------------------------------------------
<?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();
    //检查当前节点是否是内容节点。如果此节点不是内容节点,则读取器向前跳至下一个内容节点或文件结尾。
     nr.MoveToAttribute("value");
     string s=nr.Value;
     node=null;
    }
Copy after login

The above is the personal summary of reading and writing all nodes in xml and the summary of data in reading xml nodes. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


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

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

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)

Query the minimum weight in the subtree starting from node X and distance at most D Query the minimum weight in the subtree starting from node X and distance at most D Aug 25, 2023 am 11:25 AM

When doing computer programming, sometimes it is necessary to find the minimum weight of a subtree originating from a specific node, provided that the subtree cannot contain nodes that are more than D units away from the specified node. This problem arises in various fields and applications, including graph theory, tree-based algorithms, and network optimization. A subtree is a subset of a larger tree structure, with the specified node serving as the root node of the subtree. A subtree contains all descendants of the root node and their connecting edges. A node's weight refers to a specific value assigned to that node, which can represent its importance, significance, or other relevant metrics. In this problem, the goal is to find the minimum weight among all nodes in a subtree while limiting the subtree to nodes that are at most D units away from the root node. In the following article, we will delve into the complexity of mining minimum weights from subtrees

How to implement the node copy and cut functions of mind maps through Vue and jsmind? How to implement the node copy and cut functions of mind maps through Vue and jsmind? Aug 15, 2023 pm 05:57 PM

How to implement the node copy and cut functions of mind maps through Vue and jsmind? Mind map is a common thinking tool that can help us organize our thoughts and sort out our thinking logic. The node copy and cut functions are commonly used operations in mind maps, which allow us to reuse existing nodes more conveniently and improve the efficiency of thinking organization. In this article, we will use the two tools Vue and jsmind to implement the node copy and cut functions of the mind map. First, we need to install Vue and jsmind and create

What is the method to delete node in js What is the method to delete node in js Sep 01, 2023 pm 05:00 PM

The methods for deleting nodes in js are: 1. The removeChild() method is used to remove the specified child node from the parent node. It requires two parameters. The first parameter is the child node to be deleted, and the second parameter is the parent node. Node; 2. The parentNode.removeChild() method can be called directly through the parent node to delete the child node; 3. The remove() method can directly delete the node without specifying the parent node; 4. The innerHTML attribute is used to delete the node. content.

Find the shortest path between any two nodes using the Floyd-Warshal algorithm Find the shortest path between any two nodes using the Floyd-Warshal algorithm Sep 20, 2023 pm 02:21 PM

C++ has a macro, which is defined as a piece of code or an expected value, and it will be reused whenever the user needs it. The Floyd-Walshall algorithm is the process of finding the shortest path between all pairs of vertices in a given weighted graph. The algorithm follows a dynamic programming approach to find the minimum weight graph. Let us understand the meaning of Floyd-Walshall algorithm through a diagram - take vertex 1 as the source and vertex 4 as the destination and find the shortest path between them. We have seen that there are two paths that can be connected to the target vertex 4. 1->4 – the edge has a weight of 51->8->3->4 – the edge weight (1+2+1) is 4. In the given graph I, we see the smallest edge connecting two vertices. So here the vertex

Checks whether the path between two nodes in the given graph represents the shortest path Checks whether the path between two nodes in the given graph represents the shortest path Sep 07, 2023 pm 06:57 PM

To check if a given path between two centers of a graph conforms to the shortest path, this can be calculated by comparing the entire edge weight along the given path to the shortest distance between combinations of the same centers using a reliable shortest path method, such as Dijkstra's calculation or Floyd−Warshall calculation. If all edge weights on a given path match the most limited deletion, then it represents the simplest path. Also: If the overall edge weight is more prominent than the shortest distance, it indicates that there is a short distance between the two centers in the graph. Methods Used Dijkstra's Algorithm Floyd−Warshall Algorithm with Edge Reversal Cost Greedy Algorithm Dijkstra's calculation may be a popular graph traversal calculation

How to create, delete, append and replace element nodes in js (with code examples) How to create, delete, append and replace element nodes in js (with code examples) Aug 06, 2022 pm 05:26 PM

This article mainly introduces how to create, delete, append and replace element nodes in js. I hope it will be helpful to friends in need!

With the plug-in ChatGPT, it is a node, but not a center With the plug-in ChatGPT, it is a node, but not a center Apr 04, 2023 am 11:45 AM

OpenAI is a node (although an important node) in the world of robot-robot dialogue, but it is not the center. ChatGPT has launched a Plugin mechanism, which is a very exciting development. Everyone unanimously commented that "an operating system was born." This statement is completely wrong. OpenAI is a node (although an important node) in the world of robot-robot dialogue, but it is not the center. I have always had a picture in my mind: a world where robots talk to robots. People chat with a robot and let the robot help the human complete tasks through its robot friends. ChatGPT Plugin perfectly demonstrates the world

In the C program, translate the following content into Chinese: Program to find the nth node from the bottom of a linked list In the C program, translate the following content into Chinese: Program to find the nth node from the bottom of a linked list Sep 13, 2023 pm 03:13 PM

Given n nodes, the task is to print the nth node at the end of the linked list. The program must not change the order of the nodes in the list, but should only print the nth node from the last node of the linked list. Example Input-:102030405060 N=3Output-:40 In the above example, starting from the first node, traverse to count-n nodes, that is, 10,2030,40,50,60, so the third to last node is 40. Instead of traversing the entire list so efficiently the approach you can follow - get a temporary pointer to, say, temp of node type set this temporary pointer to the first node that the head pointer points to set the counter to the one in the list

See all articles