开发者

Get Values out of xml file

开发者 https://www.devze.com 2023-03-28 21:11 出处:网络
Here my code until now: public Form1() { InitializeComponent(); Configuration cfg = Configuration.Deserialize(\"config.xml\");

Here my code until now:

public Form1()
{
   InitializeComponent();

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

Here's the class for the configuration:

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; }
   }

And here's the config.xml file:

<Sensors>
  <ID1>
    <warning>70</warning>
    <alert&开发者_Go百科gt;100</alert>
  </ID1>
  <ID2>
    <warning>80</warning>
    <alert>110</alert>
  </ID2>
</Sensors>

So how can I get the correct data out of the xml file? Now I always get "0"

thanks


Use:

 System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
 xmlDoc.Load(filename);

 string sWarningValue = xmlDoc["Sensors"]["ID1"]["warning"].Value;

Didn't compile this code actually, but it should work for you.


This might work:

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

精彩评论

暂无评论...
验证码 换一张
取 消