c#提供了System.Xml.Linq操作xml文件,非常方便,本文主要介绍如何应用System.Xml.Linq读取xml文件。

xml文本

<?xml version="1.0" encoding="UTF-8"?>
<TestScript>
<default>
<id>5DC48A0B-11DC-4B40-A41E-F28AE4260538</id>
<name>SetNetworkAdapter</name>
<title>设置IP地址</title>
<desc></desc>
</default>
<channels>
<channel id="1" name="ap_agent">
<open>127.0.0.1:4754</open>
</channel>
</channels>
<actions>
<action id="1" waitResponse="false" breakOnFail="false">
<io>ap_agent</io>
<predelay>0</predelay>
<command>SetNetworkAdapter</command>
<repeat>0</repeat>
<postdelay>0</postdelay>
<params>
<param id="1" order="1" name="ip" title="ip地址" value="192.168.1.112" unit="" type="input" enable="true" limitUp="" limitDown="" hint=""/>
<param id="2" order="2" name="mask" title="子网掩码" value="255.255.255.0" unit="" type="input" enable="true" limitUp="" limitDown="" hint=""/>
<param id="3" order="3" name="gateway" title="网关" value="192.168.1.1" unit="" type="input" enable="true" limitUp="" limitDown="" hint=""/>
</params>
</action>
</actions>
</TestScript>

关键代码

public XmlAction LoadXml(string xmlFile)
{
XmlAction ret = new XmlAction();
XElement xe = XElement.Load(xmlFile);
XElement eleAction = xe.Elements("actions").Elements("action").First();
ret.Id = eleAction.Attribute("id").Value;
ret.WaitResponse = eleAction.Attribute("waitResponse").Value == "true";
ret.BreakOnFail = eleAction.Attribute("breakOnFail").Value == "true";
ret.Io = eleAction.Element("io").Value;
ret.Predelay = Convert.ToInt32(eleAction.Element("predelay").Value);
ret.Postdelay = Convert.ToInt32(eleAction.Element("postdelay").Value);
ret.Command = eleAction.Element("command").Value;
ret.Repeat = Convert.ToInt32(eleAction.Element("repeat").Value);
ret.Params = new List<Param>();
foreach (XElement para in eleAction.Elements("params").Elements("param"))
{
Param p = new Param();
ret.Params.Add(p);
p.Id = para.Attribute("id").Value;
p.Enable = para.Attribute("enable").Value == "true";
p.Hint = para.Attribute("hint").Value;
p.LimitDown = para.Attribute("limitDown").Value;
p.LimitUp = para.Attribute("limitUp").Value;
p.Name = para.Attribute("name").Value;
p.Order = para.Attribute("order").Value;
p.Title = para.Attribute("title").Value;
p.Type = para.Attribute("type").Value;
p.Unit = para.Attribute("unit").Value;
p.Value = para.Attribute("value").Value; }
return ret;
}
05-08 08:20