2011-08-17 72 views
0

這裏我的代碼至今:獲取值了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; } 
    } 

而這裏的​​3210文件:

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

所以我怎麼才能從XML文件中獲取正確的數據?現在,我總是得到 「0」

感謝

+2

是沒有任何理由的反序列化的XML?請注意,序列化或其他方式是非常昂貴的。爲什麼不把它加載到XMLDocument? – Zenwalker

回答

1

用途:

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

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

沒有實際編譯這段代碼,但它應該爲你工作。

0

這可能會實現:

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