从xml文件中获取值



我的代码到现在为止:

public Form1()
{
   InitializeComponent();
   Configuration cfg = Configuration.Deserialize("config.xml");
   textBox1.Text = cfg.warning.ToString();
}

下面是配置类:

public class Configuration
{
    int _warning;
    int _alert;
   public Configuration()
   {
     //   _warning = 50;
     //   _alert = 100;
   }
   public static void Serialize(string file, Configuration c)
   {
       XmlSerializer xs = new XmlSerializer(c.GetType());
       StreamWriter writer = File.CreateText(file);
       xs.Serialize(writer, c);
       writer.Flush();
       writer.Close();
   }
   public static Configuration Deserialize(string file)
   {
       XmlSerializer xs = new XmlSerializer(typeof(Configuration));
       StreamReader reader = File.OpenText(file);
       Configuration cfg = (Configuration)xs.Deserialize(reader);
       reader.Close();
       return cfg;
   }
   public int warning
   {
       get { return _warning; }
       set { _warning = value; }
   }
   public int alert
   {
        get { return _alert; }
        set { _alert = value; }
   }

config.xml文件:

<Sensors>
  <ID1>
    <warning>70</warning>
    <alert>100</alert>
  </ID1>
  <ID2>
    <warning>80</warning>
    <alert>110</alert>
  </ID2>
</Sensors>

那么如何从xml文件中获得正确的数据呢?现在我总是得到"0"

谢谢

使用说明:

 System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
 xmlDoc.Load(filename);
 string sWarningValue = xmlDoc["Sensors"]["ID1"]["warning"].Value;

实际上没有编译这段代码,但它应该可以为您工作。

这可能行得通:

var xdoc = XDocument.Load(pathToFile);
var warningValue = xdoc.Element("warning").Value;

相关内容

  • 没有找到相关文章

最新更新