Files
06-Note/XmlParser/Program.cs

91 lines
2.9 KiB
C#
Raw Permalink Normal View History

2023-06-20 09:22:53 +08:00
using System;
using System.IO;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;
namespace XmlParserByAttribute
{
internal class Program
{
private static void Main(string[] args)
{
m_XmlAttribute();
//m_XmlAttributeTech();
//m_XmlDocument();
//m_XmlLinq();
}
private static void m_XmlAttribute()
{
string xmlStr = @".\TestFile.xml";
XmlSerializer serializer = new XmlSerializer(typeof(CatCollection));
using (TextReader reader = new StreamReader(xmlStr))
{
CatCollection cc = serializer.Deserialize(reader) as CatCollection;
}
}
private static void m_XmlAttributeTech()
{
string xmlStr = @".\TestTeacher.xml";
XmlSerializer serializer = new XmlSerializer(typeof(Teacher));
using (TextReader reader = new StreamReader(xmlStr))
{
Teacher result = serializer.Deserialize(reader) as Teacher;
}
}
private static void m_XmlDocument()
{
string xmlStr = @".\TestFile.xml";
XmlDocument doc = new XmlDocument();
XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreComments = true;
using (XmlReader xmlReader = XmlReader.Create(xmlStr, settings))
{
doc.Load(xmlStr);
XmlNode xn = doc.SelectSingleNode("cats");
XmlNodeList itemNodes = xn.ChildNodes;
CatCollection cats = new CatCollection();
foreach (XmlNode itemNode in itemNodes)
{
Cat cat = new Cat();
// 读取节点数据赋值给 cat
cat.Color = itemNode.Attributes["color"].Value;
cat.animationType = (AnimationType)Enum.Parse(typeof(AnimationType), itemNode.Attributes["animationType"].Value, true);
var childnode = itemNode.ChildNodes;
cat.Saying = childnode.Item(0).InnerText;
cats.Cats.Add(cat);
}
}
}
private static void m_XmlLinq()
{
string xmlStr = @".\TestFile.xml";
XElement xe = XElement.Load(xmlStr);
var eles = from ele in xe.Elements()
select ele;
CatCollection cc = new CatCollection();
foreach (var ele in eles)
{
Cat cat = new Cat()
{
Color = ele.Attribute("color").Value,
animationType = (AnimationType)Enum.Parse(typeof(AnimationType), ele.Attribute("animType").Value, true),
Saying = ele.Element("saying").Value
};
cc.Cats.Add(cat);
}
}
}
}