C# XML 解析方式
今天看到了拿哥们的操作,心里倍感激动,发现.net 真的很强大,比较猛的是这个xml解析这么方便
下面就介绍一下:
写了一个sample:
?using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;
namespace XmldigersterCSharp
{
??? class Program
??? {
??????? static void Main(string[] args)
??????? {
??????????? TestXMLObject xmlObject = new TestXMLObject();
??????????? xmlObject.AnimalAge = 10;
??????????? xmlObject.AnimalEnjoy = "sing song";
??????????? xmlObject.AnimalName = "xiaoming";
??????????? xmlObject.AnimalSize="10";
??????????? Save(xmlObject,@"C:\TestXMLObject.xml");
??????? }
??????? public static void Save(TestXMLObject xmlObject, string fileName)
??????? {
??????????? try
??????????? {
??????????????? XmlSerializer xml = new XmlSerializer(typeof(TestXMLObject));
??????????????? FileStream filestream = new FileStream(fileName, FileMode.Create);
??????????????? xml.Serialize(filestream, xmlObject);
??????????????? filestream.Close();
??????????????? filestream.Dispose();
??????????? }
??????????? catch (Exception e)
??????????? {
??????????????? Console.WriteLine(e.Message);
??????????? }
??????? }
??????? public static? TestXMLObject Read(string fileName)
??????? {
??????????? try
??????????? {
??????????????? TestXMLObject xmlObject = new TestXMLObject();
??????????????? XmlSerializer xmlSerializer = new XmlSerializer(typeof(TestXMLObject));
??????????????? FileStream fs = new FileStream(fileName, FileMode.Open);
??????????????? xmlObject = (TestXMLObject)xmlSerializer.Deserialize(fs);
??????????????? return xmlObject;
??????????? }
??????????? catch (Exception e)
??????????? {
??????????????? Console.WriteLine(e.Message);
??????????????? return null;
??????????? }
??????? }
??? }
}
生成之后的代码,真强大啊哈哈
<?xml version="1.0"?>
<TestXMLObject xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
? <AnimalName>xiaoming</AnimalName>
? <AnimalAge>10</AnimalAge>
? <AnimalSize>10</AnimalSize>
? <AnimalEnjoy>sing song</AnimalEnjoy>
</TestXMLObject>
?
有什么问题请给我留言