linq to xml对xml操作很是方面。首先要引用using System.Xml.Linq。
XML文件:
<?xml version="1.0" encoding="utf-8" ?> <serverVersion> <!--最新版本--> <newVersion>3.0</newVersion> <updateReason>测试</updateReason> <serverPath>http://localhost:51523/</serverPath> <!--版本信息--> <versionInof AssemblyVersion="3.0" > <!--文件列表--> <filesInfo> <file fileName="a.txt"> <fileMD5>c81e728d9d4c2f636f067f89cc14862c</fileMD5> <filePath></filePath> <fileDownPath>versionFiles/a.txt</fileDownPath> </file> <file fileName="b.BMP"> <fileMD5>d41d8cd98f00b204e9800998ecf8427e</fileMD5> <filePath></filePath> <fileDownPath>versionFiles/b.BMP</fileDownPath> </file> <file fileName="c.wps"> <fileMD5>2d9114be8523680487371d667b6fb0f1</fileMD5> <filePath></filePath> <fileDownPath>versionFiles/c.wps</fileDownPath> </file> <file fileName="d.doc"> <fileMD5>8434f8ef821ae4f721ad6b6191191888</fileMD5> <filePath></filePath> <fileDownPath>versionFiles/d.doc</fileDownPath> </file> <file fileName="e.doc"> <fileMD5>8434f8ef821ae4f721ad6b6191191820</fileMD5> <filePath></filePath> <fileDownPath>versionFiles/e.doc</fileDownPath> </file> <file fileName="f.txt"> <fileMD5>53577514ad9fa951e39e582e442812d9</fileMD5> <filePath></filePath> <fileDownPath>versionFiles/f.txt</fileDownPath> </file> <file fileName="g.txt"> <fileMD5>df38887bc670cd288fde231beb2a3f83</fileMD5> <filePath></filePath> <fileDownPath>versionFiles/files/g.txt</fileDownPath> </file> <file fileName="h.txt"> <fileMD5>0d0fdb47733d1046190a843fcc2cf440</fileMD5> <filePath></filePath> <fileDownPath>versionFiles/h.txt</fileDownPath> </file> </filesInfo> </versionInof> </serverVersion>
一、查
XElement root=XElement.Load("../../ClientVersion.xml"); IEnumerable<XElement> files = from el in root.Elements("versionInof").Elements("filesInfo").Elements("file") where (string)el.Attribute("fileName") == fileUpdateInfo.fileName select el;
XElement.Load("../../ClientVersion.xml")//创建的是xml文件的根节点,包含了整个XML。相当于是<span style="font-family: Arial,Helvetica,sans-serif;">serverVersion节点的内容</span>
<pre name="code" class="csharp" style="font-size: 14px;">root.Elements("versionInof")//是查root节点下<span style="font-family: Arial,sans-serif;">的所有节点 名为</span><span style="font-family: Arial,sans-serif;">versionInof,注意这里是仅仅是root节点下的子节点,如果是子节点下的子节点是不能被查询到的</span>
<span style="font-family: Arial,sans-serif;"></span><pre name="code" class="csharp" style="font-size: 14px;">root.Element("节点名");//返回的是"节点名"的第一个节点
节点.Attribute("属性名");//查的是该节点的属性名为“属性名”的值,如<span style="font-family: Arial,sans-serif;"><versionInof AssemblyVersion="3.0" >中的3.0</span>
节点.value;//是该节点的文本,如<span style="font-family: Arial,sans-serif;"><fileMD5>df38887bc670cd288fde231beb2a3f83</fileMD5>中的</span><span style="font-family: Arial,sans-serif;">df38887bc670cd288fde231beb2a3f83</span>