C# XML解析
通过XML属性解析
XML文件
<?xml version="1.0" encoding="utf-8" ?>
<Lists>
<List>
<Item CN="CN1" EN="SN1">Item1</Item>
<Item CN="CN2" EN="SN2">Item2</Item>
<Item CN="CN3" EN="SN3">Item3</Item>
<Item CN="CN4" EN="SN4">Item4</Item>
<Item CN="CN5" EN="SN5">Item5</Item>
</List>
<key>
<ID id="1">id</ID>
<Name name="2">name</Name>
</key>
</Lists>
解析
XmlDocument doc = new XmlDocument();
//doc.LoadXml("XML字符串");
doc.Load("XML文件路径");
var listNodes = doc.SelectSingleNode("Lists").ChildNodes[0];//表示Lists下的List的所有数据
var keyNodes = doc.SelectSingleNode("Lists").ChildNodes[1];//表示Lists下的key的所有数据
#region 获取属性的值
//获取属性的值
string CN1 = listNodes.SelectSingleNode("Item").Attributes["CN"].Value;//SelectSingleNode 表示第一个
CN1 = ((XmlElement)listNodes.SelectSingleNode("Item")).GetAttribute("CN");
CN1 = listNodes.SelectNodes("Item")[0].Attributes["CN"].Value; //SelectNodes 表示查询所有
CN1 = doc.SelectSingleNode("Lists/List/Item").Attributes["CN"].Value;
CN1 = doc.SelectNodes("Lists/List/Item")[0].Attributes["CN"].Value;
string EN2 = listNodes.SelectNodes("Item")[1].Attributes["EN"].Value; //SelectNodes 表示查询所有
EN2 = doc.SelectNodes("Lists/List/Item")[1].Attributes["EN"].Value;
string one = keyNodes.SelectSingleNode("ID").Attributes["id"].Value;
string two = keyNodes.SelectSingleNode("Name").Attributes["name"].Value;
#endregion
#region 获取节点的值
//获取节点的值
string Item1 = doc.SelectSingleNode("Lists/List/Item").InnerText;
Item1 = listNodes.SelectSingleNode("Item").InnerText;
string Item2 = doc.SelectNodes("Lists/List/Item")[1].InnerText;
string id = doc.SelectSingleNode("Lists/key/ID").InnerText;
string name = doc.SelectSingleNode("Lists/key/Name").InnerText;
id = keyNodes.SelectSingleNode("ID").InnerText;
name = keyNodes.SelectSingleNode("Name").InnerText;
#endregion
#region 循环遍历读取,添加至 Dictionary
Dictionary<string, string> dic = new Dictionary<string, string>();
var nodes = doc.SelectSingleNode("Lists/key").ChildNodes;
foreach (XmlNode item in nodes)
{
XmlElement xe = (XmlElement)item;
string id2 = xe.GetAttribute("id");//属性
dic.Add(xe.Name, xe.InnerText);
}
string id3 = dic.FirstOrDefault(q => q.Key == "ID").Value;
#endregion
XML转换对象
XML序列化和反序列化
public class XMLExtensions
{
/// <summary>
/// 对象序列化为XML字符串
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="t">Model实体对象</param>
/// <returns></returns>
public static string Serialize<T>(T t)
{
using (StringWriter sw = new StringWriter())
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
xmlSerializer.Serialize(sw, t);
return sw.ToString();
}
}
/// <summary>
/// XML反序列化为对象
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="xml">xml字符串</param>
/// <returns></returns>
public static T Deserialize<T>(string xml)
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
using StringReader stringReader = new StringReader(xml);
return (T)xmlSerializer.Deserialize(stringReader);
}
}
XMLHelper类
using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace ConsoleApp2
{
/// <summary>
/// XML工具类
/// </summary>
public static class XmlHelper
{
/// <summary>
/// 将一个对象序列化为XML字符串。这个方法将不生成XML文档声明头。
/// </summary>
/// <param name="o">要序列化的对象</param>
/// <returns>序列化产生的XML字符串</returns>
public static string XmlSerializerObject(object o)
{
Encoding encoding = Encoding.UTF8;
XmlSerializer serializer = new XmlSerializer(o.GetType());
using (MemoryStream stream = new MemoryStream())
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.NewLineChars = "\r\n";
settings.Encoding = encoding;
settings.OmitXmlDeclaration = true;
settings.IndentChars = " ";
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
using (XmlWriter writer = XmlWriter.Create(stream, settings))
{
serializer.Serialize(writer, o, ns);
writer.Close();
}
//return Encoding.UTF8.GetString(stream.ToArray());
stream.Position = 0;
using (StreamReader reader = new StreamReader(stream, encoding))
{
return reader.ReadToEnd();
}
}
}
private static void XmlSerializeInternal(Stream stream, object o, Encoding encoding)
{
XmlSerializer serializer = new XmlSerializer(o.GetType());
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.NewLineChars = "\r\n";
settings.Encoding = encoding;
settings.IndentChars = " ";
using (XmlWriter writer = XmlWriter.Create(stream, settings))
{
serializer.Serialize(writer, o);
}
}
/// <summary>
/// 将一个对象序列化为XML字符串
/// </summary>
/// <param name="o">要序列化的对象</param>
/// <param name="encoding">编码方式</param>
/// <returns>序列化产生的XML字符串</returns>
public static string XmlSerialize(object o, Encoding encoding)
{
using (MemoryStream stream = new MemoryStream())
{
XmlSerializeInternal(stream, o, encoding);
stream.Position = 0;
using (StreamReader reader = new StreamReader(stream, encoding))
{
return reader.ReadToEnd();
}
}
}
/// <summary>
/// 将一个对象按XML序列化的方式写入到一个文件(采用UTF8编码)
/// </summary>
/// <param name="o">要序列化的对象</param>
/// <param name="path">保存文件路径</param>
public static void XmlSerializeToFile(object o, string path)
{
XmlSerializeToFile(o, path, Encoding.UTF8);
}
/// <summary>
/// 将一个对象按XML序列化的方式写入到一个文件
/// </summary>
/// <param name="o">要序列化的对象</param>
/// <param name="path">保存文件路径</param>
/// <param name="encoding">编码方式</param>
public static void XmlSerializeToFile(object o, string path, Encoding encoding)
{
using (FileStream file = new FileStream(path, FileMode.Create, FileAccess.Write))
{
XmlSerializeInternal(file, o, encoding);
}
}
/// <summary>
/// 从XML字符串流中反序列化对象
/// </summary>
/// <param name="stream">包含对象的XML字符串流</param>
/// <param name="destType">要序列化的目标类型</param>
/// <returns>反序列化得到的对象</returns>
public static object XmlDeserialize(Stream stream, Type destType)
{
XmlSerializer mySerializer = new XmlSerializer(destType);
using (StreamReader sr = new StreamReader(stream))
{
return mySerializer.Deserialize(sr);
}
}
/// <summary>
/// 从XML字符串中反序列化对象
/// </summary>
/// <param name="s">包含对象的XML字符串</param>
/// <param name="destType">要序列化的目标类型</param>
/// <param name="encoding">编码方式</param>
/// <returns>反序列化得到的对象</returns>
public static object XmlDeserialize(string s, Type destType, Encoding encoding)
{
using (MemoryStream ms = new MemoryStream(encoding.GetBytes(s)))
{
return XmlDeserialize(ms, destType);
}
}
/// <summary>
/// 从XML字符串中反序列化对象
/// </summary>
/// <typeparam name="T">结果对象类型</typeparam>
/// <param name="s">包含对象的XML字符串</param>
/// <returns>反序列化得到的对象</returns>
public static T XmlDeserialize<T>(string s)
{
return (T)XmlDeserialize(s, typeof(T), Encoding.UTF8);
}
/// <summary>
/// 读入一个文件,并按XML的方式反序列化对象。
/// </summary>
/// <typeparam name="T">结果对象类型</typeparam>
/// <param name="path">文件路径</param>
/// <returns>反序列化得到的对象</returns>
public static T XmlDeserializeFromFile<T>(string path)
{
using (FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read))
{
return (T)XmlDeserialize(fs, typeof(T));
}
}
/// <summary>
/// 获取XML跟节点的值
/// </summary>
/// <param name="path">文件路径</param>
/// <returns></returns>
public static string XmlGetElementName(string path)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(path);
return xmlDoc.DocumentElement.Name;
}
}
}
XML文件
<?xml version="1.0" encoding="utf-8"?>
<Entity xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Id="04f16101-0256-4228-b7a8-08d95590738f" Name="测试名称" DisplayName="备注">
<Status StatusId="ca119874-1788-479f-b79b-08d95590738z">成功</Status>
<Tags>标签A</Tags>
<Tags>标签B</Tags>
<Tags>标签C</Tags>
<Attributes>
<Attribute Status="1" Type="type">
<Id>ca119874-1788-479f-b79b-08d95590738f</Id>
<Name>张三</Name>
</Attribute>
<Attribute Status="2" Type="type">
<Id>ca119874-1788-479f-b79b-08d955907382</Id>
<Name>李四</Name>
</Attribute>
</Attributes>
</Entity>
XML转换成对象
var Metadata = XmlHelper.XmlDeserializeFromFile<Entity>(@"F:\DownLoad\Test2.xml");
实体类
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
namespace ConsoleApp2
{
[XmlRoot("Entity")]
public class Entity
{
[XmlAttribute("Id")]
public Guid EntityId { get; set; }
[XmlAttribute]
public string Name { get; set; }
[XmlAttribute]
public string DisplayName { get; set; }
[XmlElement("Status")]
public StatusEntity StatusEntity { get; set; }
//[XmlArrayItem("Attribute")] //和[XmlType("Attribute")] 效果一样
[XmlArray("Attributes")]
public List<Attributes> Attributes { get; set; }
[XmlElement("Tags")]
public List<string> Tags { set; get; }
[XmlIgnore]
public string Name2 { get; set; }
}
[XmlRoot("Status")]
public class StatusEntity
{
[XmlAttribute("StatusId")]
public string Id { get; set; }
[XmlText]
//获取Status 节点的值
public string Value { get; set; }
}
[XmlType("Attribute")]
public class Attributes
{
[XmlElement("Id")]
public Guid AttributeId { get; set; }
[XmlAttribute("Type")]
public string Type { get; set; }
[XmlElement]
public string Name { get; set; }
}
}