最近在做一个demo的时候需要读取xml文件中的指定数据,从网上找到的程序都太复杂,只好用linq to xml来操作了(不得不说这真的是个好东西!),下面说一下代码。
这是要读取的目标xml文件:
<?xml version="1.0" encoding="utf-8"?>
<memoSets>
<memoSet Form="MainForm">
<memoColorName>ff7aa2c5</memoColorName>
<memoColorA>255</memoColorA>
<memoColorR>122</memoColorR>
<memoColorG>162</memoColorG>
<memoColorB>197</memoColorB>
<memoFontName>宋体</memoFontName>
<memoFontSize>9</memoFontSize>
<memoFontStytle>0</memoFontStytle>
<memoFontGraUt>3</memoFontGraUt>
<memoFontGDICS>134</memoFontGDICS>
<memoFontGDIVF>False</memoFontGDIVF>
</memoSet>
</memoSets>
C#中的代码:
1.添加命名空间 using System.Xml.Linq;
2.程序(注释中都有说明)
//将xml文件加载到新的XElement 中
XElement xe1 = XElement.Load(“要读取的xml文件的路径”);
//创建IEnumerable泛型接口,将memoset中Form属性为MainForm的元素提取出来
IEnumerable<XElement> element1 = from element in xe1.Elements("memoSet")
where element.Attribute("Form").Value == "MainForm"
select element;
//将元素中节点名字为memoColorName的值提取出来,再转换为string类型,当然也可以转换为其它的类型
string str1 = Convert.ToString(element1.First().Element("memoColorName").Value);
string str2= Convert.ToString(element1.First().Element("memoColorA").Value);
3.如果要读取指定的属性的话,可以添加
string str2= Convert.ToString(element1.First().Attribute("Form").Value);
总结:程序大致就是这样,先读取xml文件,再读取所需的元素,最后读取相应的节点或属性,比较简单,有疑问的话欢迎留言,也欢迎转载!