C#读取XML中元素和属性值的实现代码

1、school.xml,如下:

代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<!--启明培训学校学生信息:
    1、一年级学生
    2、二年级学生 
  -->
  <school name="启明培训学校">
    <grades>
     <grade id="1" name="一年级">
         <classes>
         <class id="101" name="一班">
                 <teachers>
                    <teacher teach="语文"><teacherName><![CDATA[王军]]></teacherName></teacher>
                    <teacher teach="数学"><teacherName><![CDATA[周杰]]></teacherName></teacher>                             
                 </teachers>
                 <students>
                     <student id="10101">
                         <name>亢阳</name>
                          <sex>女</sex>
                     </student>
                     <student id="10102">
                         <name>田镇南</name>
                         <sex>男</sex>
                     </student>
                     <student id="10103">
                         <name>刘嘉</name>
                         <sex>女</sex>
                     </student>
                 </students>
         </class>
        </classes>
     </grade>
        <grade id="2" name="二年级">
         <classes>
         <class id="201" name="二班">
                 <teachers>
                    <teacher teach="语文"><teacherName><![CDATA[胡军]]></teacherName></teacher>
                    <teacher teach="数学"><teacherName><![CDATA[王洁]]></teacherName></teacher>            
                 </teachers>
                 <students >
                     <student id="20101">
                         <name>胡艳</name>
                          <sex>女</sex>
                     </student>
                     <student id="20102">
                         <name>张三</name>
                         <sex>男</sex>
                     </student>
                     <student id="20103">
                         <name>李四</name>
                         <sex>女</sex>
                     </student>
                 </students>
         </class>
        </classes>
     </grade>
</grades>    
  </school>

2、XMLReader.cs (我用的是控制台应用程序,直接附上全部代码吧) 


代码如下:

using System;
   using System.Collections.Generic;
   using System.Linq;
   using System.Text;
   using System.Xml;
   namespace XMLReader
   {
     class XMLReader
     {
         static void Main(string[] args)
         {
             string xmlFilePath = "school.xml";
             XmlDocument doc = new XmlDocument();
             doc.Load(xmlFilePath);

//学校  使用xpath表达式选择文档中所有的schoo的子节点
             XmlNodeList schoolNodeList = doc.SelectNodes("/school");
             if (schoolNodeList != null)
             {
                 foreach (XmlNode schoolNode in schoolNodeList)
                 {
                     //通过Attributes获得属性名为name的属性
                     string schoolName = schoolNode.Attributes["name"].Value;
                     Console.WriteLine("学校:" + schoolName);

#region 年级
                     //通过SelectSingleNode方法获得当前节点下的grades子节点
                     XmlNode gradesNode = schoolNode.SelectSingleNode("grades");
                     if (gradesNode != null)
                     {
                         //通过ChildNodes属性获得grades的所有一级子节点
                         XmlNodeList gradeNodeList = gradesNode.ChildNodes;
                         if (gradeNodeList != null)
                         {
                             foreach (XmlNode gradeNode in gradeNodeList)
                             {
                                 Console.WriteLine("\t");
                                 Console.WriteLine("年级:" + gradeNode.Attributes["name"].Value + "   ID:" + gradeNode.Attributes["id"].Value);

#region 班级
                                 //通过SelectSingleNode方法获得当前节点下的classes子节点
                                 XmlNode classesNode = gradeNode.SelectSingleNode("classes");
                                 if (classesNode != null)
                                 {
                                     //通过ChildNodes属性获得classes的所有一级子节点
                                     XmlNodeList classNodeList = classesNode.ChildNodes;
                                     if (classNodeList != null)
                                     {
                                         foreach (XmlNode classNode in classNodeList)
                                         {
                              Console.WriteLine("  班级:" + classNode.Attributes["name"].Value + "    ID:" + classNode.Attributes["id"].Value);

#region 老师
                                             XmlNode teachersNode = classNode.SelectSingleNode("teachers");
                                             if (teachersNode != null)
                                             {
                                                 XmlNodeList teacherNodeList = teachersNode.ChildNodes;
                                                 if (teacherNodeList != null)
                                                 {
                                                     foreach (XmlNode teacherNode in teacherNodeList)
                                                     {                                              
                                                         XmlNode teacherNameNode = teacherNode.FirstChild;
                                                         XmlCDataSection cdate = (XmlCDataSection)teacherNameNode.FirstChild;
                                                         if (cdate != null)
                                                         {
                                             Console.WriteLine("   "+teacherNode.Attributes["teach"].Value + "老师:"+cdate.InnerText.Trim());

}
                                                     }
                                                 }
                                             }
                                             #endregion  老师

#region 所有学生
                                                 XmlNode studentsNode = classNode.SelectSingleNode("students");
                                                 if (studentsNode != null)
                                                 {
                                                     XmlNodeList studentNodeList = studentsNode.ChildNodes;
                                                     if (studentNodeList != null)
                                                     {
                                                         foreach (XmlNode studentNode in studentNodeList)
                                                         {
                                                             Console.WriteLine("    学生:" + studentNode.Attributes["id"].Value);

//获取student的属性值name和文本
                                                             XmlNode stu1 = studentNode.FirstChild;
                                                             XmlElement xe1 = (XmlElement)stu1;
                                                             if (xe1 != null)
                                                             {
                                                                 Console.WriteLine("        姓名:" + xe1.InnerText.Trim());
                                                             }
                                                             //获取student的属性值sex和文本
                                                             XmlNode stu2 = studentNode.LastChild;
                                                             XmlElement xe2 = (XmlElement)stu2;
                                                             if (xe2 != null)
                                                             {
                                                                 Console.WriteLine("        姓别:" + xe2.InnerText.Trim());
                                                             }
                                                         }
                                                     }
                                                 #endregion 所有学生
                                                 }
                                             }
                                         }
                                 #endregion 班级
                                     }
                                 }
                             }
                     #endregion  年级
                             Console.Write("\r\n按随意键跳出");
                             Console.ReadKey();
                         }

}
                 }
             }
         }
     }

ok,运行,如图:

(0)

相关推荐

  • c#通过xpath读取xml示例

    需要修改Main方法第一行代码的路径为你的books.xml文件绝对路径或相对路径.代码演示了XPath各种语法的使用情况 books.xml 复制代码 代码如下: <?xml version="1.0" encoding="ISO-8859-1"?><bookstore> <book category="COOKING">    <title lang="en">Everyda

  • c#读取xml文件到datagridview实例

    复制代码 代码如下: using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.IO;using System.Xml;using System.Xml.Linq; namespa

  • c#读取XML多级子节点

    话不多说,请看代码: string xmlFilePath = "D:\\log_xml\\MarInfo.xml"; //Server.MapPath(@"相对路径如/xml/test.xml"); XmlDocument doc = new XmlDocument(); doc.Load(xmlFilePath);//加载XML文件 string rst = ""; //使用xpath表达式选择文档中所有的student子节点 XmlNode

  • 基于C#中XmlReader读取Xml的深入分析

    XmlDocument和XElement在读取Xml时要将整个Xml文档放到内存中去操作,这样做操作简单,但是很费内存,而在有些场景下我们必须考虑尽可能节省内存.这时候就该XmlReader和XmlWriter出场了.XmlReader读取Xml需要通过Read()实例方法,不断读取Xml文档中的声明,节点开始,节点内容,节点结束,以及空白等等,直到文档结束,Read()方法返回false.如下读取Xml内容实例代码和注释说明 复制代码 代码如下: using System; using Sys

  • C#读取xml节点数据方法小结

    本文实例总结了C#读取xml节点数据的方法.分享给大家供大家参考.具体如下: 第一种: 使用XPath XML的路径我配置在web.config 的appSettings节点下 <appSettings> <add key="orgCodePath" value="../../template/home/orgCode.xml"/> </appSettings> XML结构如下: <?xml version="1.

  • 简介C#读取XML的两种方式

    XML作用 对于XML,想必各位都比较了解,我也就不用费笔墨来描述它是什么了,我想在未来的Web开发中XML一定会大放异彩,XML是可扩展标记语言,使用它企业可以制定一套自己的数据格式.用于Internet的数据传输,我想,这是XML对于我们这些程序员最诱人的地方! 我们今天的主题不是论述XML的好处,而是讨论在C#中如何使用XML.下面我们来了解一下使用程序访问XML的一些基础理论知识. 访问的两种模型: 在程序中访问进而操作XML文件一般有两种模型,分别是使用DOM(文档对象模型)和流模型,

  • C# Linq读取XML文件的实例

    1.示例XML文件:Demo.xml 复制代码 代码如下: <?xml version="1.0" encoding="utf-8" ?><note>  <conf>    <to>infozero</to>    <from>lerroy</from>    <heading>测试信息</heading>    <body>第一条测试信息<

  • 在C#中创建和读取XML文件的实现方法

    1.创建简单的XML文件为了便于测试,我们首先创建控制台应用程序,项目命名为CreateXml,Program.cs代码如下: 复制代码 代码如下: using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Xml; namespace CreateXml{    class Program    {        static void Main(string[]

  • c# winform读取xml文件创建菜单的代码

    复制代码 代码如下: using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using WinformMenu.Helper;using System.Xml; namespace WinformMen

  • C#读取XML中元素和属性值的实现代码

    1.school.xml,如下: 复制代码 代码如下: <?xml version="1.0" encoding="UTF-8"?><!--启明培训学校学生信息:    1.一年级学生    2.二年级学生    -->  <school name="启明培训学校">    <grades>     <grade id="1" name="一年级">

  • 原生javascript获取元素样式属性值的方法

    所以, 我们得利用IE的currentStyle和W3C的getPropertyValue获取. elem.style.attr获取样式的方法就不说了. 先来看currentStyle方法, 此对象ie专属, 代表了在全局样式表.内嵌样式和 HTML 标签属性中指定的对象格式和样式. IE下通过它, 就可以获取元素的Css属性值. 而针对其他标准浏览器, W3C也提供了一个方法getPropertyValue, 此方法, 稍有点复杂, 首先要通过document.defaultView.getC

  • JS实现查找数组中对象的属性值是否存在示例

    本文实例讲述了JS实现查找数组中对象的属性值是否存在.分享给大家供大家参考,具体如下: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <script> var studentsArray = [ { "

  • 使用vue点击li,获取当前点击li父辈元素的属性值方法

    vue实现加载并展示后台数据的tab选项卡 vue用于渲染页面 jquery用于方法实现动态效果 <div class="content"> <!-- change方法, 数值改变触发 --> <select v-on:change="getData()" name="" id="dataSelect"> <option value="" v-bind:name=&

  • python 如何读取列表中字典的value值

    目录 读取列表中字典的value值 获取字典的key和value 读取列表中字典的value值 list = [{"name": "推荐食谱", "1": "症状", "name1": "浑身忽冷忽热"}, {"name": "绿豆薏米饭"}, {"name": "芝麻"}] res = [item[key]

  • php有序列表或数组中删除指定的值的实现代码

    实现:删除给定的值之后,得到一个新的有序列表,长度-1 代码: <?php /** * Created by PhpStorm. * User: wkk * Time: 2021/7/11 - 01:03 * Desc: <线性表> */ namespace php; class ListArray { // 从一个线性表中删除给定的值 public function deleteValue($list, $value) { // 记录是否找到 $flag = false; // 记录这

  • 在AndroidManifest.xml中uses-sdk内属性意思

    在AndroidMenifest.xml中,常常会有下面的语句: 复制代码 代码如下: <uses-sdk android:minSdkVersion="4" android:targetSdkVersion="10" android:maxSdkVersion="10" /> 在default.properties中,会看到下面的语句: target=android-10 如果是使用Eclipse的话,还可能会看到这样的警告: At

  • ajax中的async属性值之同步和异步及同步和异步区别

    jquery中ajax方法有个属性async用于控制同步和异步,默认是true,即ajax请求默认是异步请求,有时项目中会用到AJAX同步.这个同步的意思是当JS代码加载到当前AJAX的时候会把页面里所有的代码停止加载,页面出现假死状态,当这个AJAX执行完毕后才会继续运行其他代码页面假死状态解除.而异步则这个AJAX代码运行中的时候其他代码一样可以运行. ajax中async这个属性,用于控制请求数据的方式,默认是true,即默认以异步的方式请求数据. 一.async值为true (异步) 当

  • XML文件修改节点属性值(多种方法)

    xml 文件内容: 复制代码 代码如下: <?xml version="1.0" encoding="utf-8"?> <subtitles> <info> <content>最新通告:五一放假七天!请各教员悉知</content> <speed>4</speed> <color>red</color> </info> </subtitles

  • Java 采用反射获取class属性值的实现代码

    原理:Java的反射能够获取属性的名称,然后通过invoke调用类的某个方法.比如有个属性叫userName,这个类写了个方法叫getUserName,通过invoke调用getUserName这个方法.代码如下 复制代码 代码如下: import java.lang.reflect.Field;import java.lang.reflect.Method;import java.util.HashMap;import java.util.Map;public class ParameterB

随机推荐