【问题标题】:Get Values out of xml file从 xml 文件中获取值
【发布时间】:2023-03-29 05:50:02
【问题描述】:

到目前为止,这是我的代码:

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”

谢谢

【问题讨论】:

  • 你有什么理由反序列化 xml 吗?请注意,序列化或其他方式非常昂贵。为什么不直接将其加载到 XMLDocument 中??

标签: c# xml config


【解决方案1】:

用途:

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

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

实际上并没有编译这段代码,但它应该适合你。

【讨论】:

    【解决方案2】:

    这可能有效:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-18
      • 2012-05-26
      • 2023-03-29
      • 1970-01-01
      • 2014-01-17
      • 1970-01-01
      相关资源
      最近更新 更多