在日常开发过程中,有时需要保存到本地一些结构化数据或者配置信息,或者与其他系统通信时,通过xml方式来读取数据。
下面有两文件,一个是带有id属性的xml文件,一个不带属性的简单xml文件。
带属性的xml文件
<?xml version="1.0" encoding="utf-8" ?>
<studentList>
<student>
<name id="1003">张三</name>
<sex>男</sex>
<age >20</age>
</student>
</studentList>
不带属性的xml文件
<?xml version="1.0" encoding="utf-8" ?>
<studentList>
<student>
<name>张三</name>
<sex>男</sex>
<age>20</age>
</student>
</studentList>
第一种方式:通过DataSet读取
这种方式最简单,而且取数据也很方便,但是对于比较复杂的xml,操作起来也很麻烦,每一个带属性的节点都会生成一个table,可以自行监视下DataSet的结构情况,然后做不同的处理
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ReadXML
{
internal class Program
{
static void Main(string[] args)
{
//1.先拿到需要读取的 xml文件路径
//先获取Program.cs 的 路径
string root = Path.GetFullPath(Path.Combine(
Path.GetDirectoryName(typeof(Program).Assembly.Location)));
//拼接 XML目录
string xmlPath = Path.GetFullPath(Path.Combine(root, "XML\\不带属性的文件.xml"));
string xmlPaths = Path.GetFullPath(Path.Combine(root, "XML\\带属性文件.xml"));
//2.通过dataset读取简单xml文件
DataSet ds = new DataSet();
ds.ReadXml(xmlPath);
//读取第一条数据的name节点
string name = ds.Tables[0].Rows[0]["name"].ToString();
//输出:张三
Console.WriteLine(name);
//3.通过dataset读取带属性的xml文件
ds = new DataSet();
ds.ReadXml(xmlPaths);
//读取的节点名称
string nodeName = "name";
name = ds.Tables[nodeName].Rows[0][nodeName + "_Text"].ToString();
//读取节点的id属性
string id = ds.Tables[nodeName].Rows[0]["id"].ToString();
//输出:id:1,name:张三
Console.WriteLine("id:{0},name:{1}", id, name);
Console.ReadKey();
}
}
}
第二种方式:通过XmlDocument(推荐使用)
这种方式就很强大并且灵活了,根据节点顺序逐步获取就可以
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//需导入命名空间 (方式二)
using System.Xml;
namespace ReadXML
{
internal class Program
{
static void Main(string[] args)
{
//先获取Program.cs 的 路径
string root = Path.GetFullPath(Path.Combine(
Path.GetDirectoryName(typeof(Program).Assembly.Location)));
//拼接 XML目录
string xmlPath = Path.GetFullPath(Path.Combine(root, "XML\\不带属性的文件.xml"));
string xmlPaths = Path.GetFullPath(Path.Combine(root, "XML\\带属性文件.xml"));
//XmlDocument读取xml文件
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlPaths);
//获取xml根节点
XmlNode xmlRoot = xmlDoc.DocumentElement;
//根据节点顺序逐步读取
//读取第一个name节点
string name = xmlRoot.SelectSingleNode("student/name").InnerText;
//读取节点的id属性
string id = xmlRoot.SelectSingleNode("student/name").Attributes["id"].InnerText;
//输出:id:1,name:张三
Console.WriteLine("id:{0},name:{1}", id, name);
//读取所有的name节点
foreach (XmlNode node in xmlRoot.SelectNodes("student/name"))
{
//循环输出
Console.WriteLine("id:{0},name:{1}", node.Attributes["id"].InnerText, node.InnerText);
}
Console.ReadKey();
}
}
}
第三种方式:使用JSON.NET
使用JSON.NET可以将xml转换成json去操作
如果是对xml文件进行操作的话,需要引入Newtonsoft.Json.dll,使用时请注意版本,低版本可能不支持
1.引用Newtonsoft.Json.dll
安装最新的就行
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//需导入命名空间 (方式二)
using System.Xml;
//需导入命名空间 (方式三)
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace ReadXML
{
internal class Program
{
static void Main(string[] args)
{
//先获取Program.cs 的 路径
string root = Path.GetFullPath(Path.Combine(
Path.GetDirectoryName(typeof(Program).Assembly.Location)));
//拼接 XML目录
string xmlPath = Path.GetFullPath(Path.Combine(root, "XML\\不带属性的文件.xml"));
string xmlPaths = Path.GetFullPath(Path.Combine(root, "XML\\带属性文件.xml"));
//XmlDocument读取xml文件
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlPaths);
//转换为json
string json = JsonConvert.SerializeXmlNode(xmlDoc);
//解析json
JObject jobj = JObject.Parse(json);
string ss = "["+jobj["studentList"]["student"].ToString()+"]";
JArray jarr =new JArray();
try
{
//Newtonsoft.Json.Linq.JArray.Parse 是用来解析数组的
jarr = JArray.Parse(ss);//注意:Parse 解析的内容必须有"[]"括起来
}
catch (Exception ex)
{
Console.WriteLine("解析失败," + ex.Message);
return;
}
//输出:id:1,name:张三
Console.WriteLine("id:{0},name:{1}", jarr[0]["name"]["@id"], jarr[0]["name"]["#text"]);
Console.ReadKey();
}
}
}
参考:mp.weixin.qq.com/s/E3Vq8m5rI… 代码地址:github.com/18269269032…