2017-04-10 47 views
-1

我有一個xml文件,我想在文本文件中讀取。它必須作爲文本(而不是代碼本身)發佈。我現在所擁有的:(在一個打開xml文件的按鈕中)。我現在可以打開文件並將其放入文本框中,但是按照說明,它僅顯示代碼,不顯示我想要查看的計算結果。在c#中讀取xml文件wpf

XmlDocument xmldoc = new XmlDocument(); 
     XmlNodeList xmlnode; 
     int i = 0; 
     string str = null; 
     OpenFileDialog openFileDialog = new OpenFileDialog(); 
     if (openFileDialog.ShowDialog() == true) 
      tbBerekeningen.Text = File.ReadAllText(openFileDialog.FileName); 
     xmldoc.Load(tbBerekeningen.Text); 
     xmlnode = xmldoc.GetElementsByTagName("Product"); 
     for (i = 0; i <= xmlnode.Count - 1; i++) 
     { 
      xmlnode[i].ChildNodes.Item(0).InnerText.Trim(); 
      str = xmlnode[i].ChildNodes.Item(0).InnerText.Trim() + " " + xmlnode[i].ChildNodes.Item(1).InnerText.Trim() + " " + xmlnode[i].ChildNodes.Item(2).InnerText.Trim(); 
      MessageBox.Show(str); 

XML文件是任何其他的XML文件:

元素

<Som> 
<Getal1>1</Getal1> 
    <Operator>+</Operator> 
<Getal2>34</Getal2> 
</Som> 
+0

xmldoc.GetElementsByTagName(「Product」)。 XML文件是否有一個名爲Product的元素? (您之前發佈的xml不包含此元素) – Johan

+0

您需要更好地解釋問題所在。我們不知道你需要什麼計算。 – jdweng

+0

@Johan我編輯過帖子,是的,我沒有。但即使當我把「索姆」它仍然給出了整個XML代碼 – user6840583

回答

0

嘗試下面的代碼:

XmlDocument xmldoc = new XmlDocument(); 
     XmlNodeList xmlnode; 
     int i = 0; 
     string str = null; 
     string result = string.Empty; 
     List<int> Value1 = new List<int>(); 
     List<int> Value2 = new List<int>(); 
     List<string> Operator = new List<string>(); 
     OpenFileDialog openFileDialog = new OpenFileDialog(); 
     if (openFileDialog.ShowDialog() == true) 
     { 

      xmldoc.Load(openFileDialog.FileName); 
      xmlnode = xmldoc.GetElementsByTagName("Som"); 
      for (i = 0; i <= xmlnode.Count - 1; i++) 
      { 
       xmlnode[i].ChildNodes.Item(0).InnerText.Trim(); 
       str = str + xmlnode[i].ChildNodes.Item(0).InnerText.Trim() + " " + xmlnode[i].ChildNodes.Item(1).InnerText.Trim() + " " + xmlnode[i].ChildNodes.Item(2).InnerText.Trim() + System.Environment.NewLine; 
       Value1.Add(int.Parse(xmlnode[i].ChildNodes.Item(0).InnerText.Trim())); 
       Value2.Add(int.Parse(xmlnode[i].ChildNodes.Item(2).InnerText.Trim())); 
       Operator.Add(xmlnode[i].ChildNodes.Item(1).InnerText.Trim()); 
      } 
      tbBerekeningen.Text = str; 
     } 
     for (int j = 0; j < Value1.Count; j++) 
     { 
      if (Operator[j] == "+") 
      { 
       result = result + Value1[j] + Value2[j] + System.Environment.NewLine; 
      } 

      //add if else block or switch cases for all the operators. 
      //e.g if (Operator[j] == "-") 

     } 

     tbBerekeningen.Text = result; 

你可以看到在MessageBox中所有的計算爲循環進展。

+0

嗯,它的工作原理,所以謝謝,但有什麼辦法來顯示「tbCalculations」中的計算(不是在消息框)? – user6840583

+0

編輯我的代碼示例。它現在將顯示「tbCalculations」中的所有計算。 –

+0

太棒了!就像預期的一樣!只是一個額外的東西:我怎麼能讓它計算出數字? – user6840583