2011-06-17 144 views
0

我有這樣獲取父屬性值XML

< insrtuction名= INST1>

< destnation>
<連接> con 1的 < /連接> < /目的地> XML文件

< destreat>
<連接> CON2 < /連接> < /目的地>

< /指令>

< insrtuction名稱= INST2>

< destnation>
<連接> CON3 < /連接> </destination>

< destnation>
<連接> CON4 < /連接> < /目的地>

< /指令>

我已經把所有的連接。代碼我寫

private void button5_Click(object sender, EventArgs e) 
    { 
     xml = new XmlDocument(); 
     xml.Load("D:\\connections.xml"); 
     string text = ""; 
     XmlNodeList xnList = xml.SelectNodes("/instruction/destination"); 
     foreach (XmlNode xn in xnList) 
     { 
      string configuration = xn["connection"].InnerText;    
      text = text + configuration + "\r\n" + "\r\n"; 
     } 
     textBox1.Text=text; 
    }   

輸出我得到的是

con1 
con2 
con3 
con4 

根據我的新要求輸出應該

Instruction Name : inst1 
connection: con1 
connection: con1 
Instruction Name : inst2 
connection: con3 
connection: con4 

我是新來的.NET,我使用2.0幀的工作,我不能使用LINQ。由於

+0

什麼是你遇到困難? – 2011-06-17 06:25:56

+0

@Steve B我試圖這樣做 string instruction = xn [「Instruction」]。GetElementsByTagName(「name」)。ToString(); 但它的投擲錯誤 – Gokul 2011-06-17 06:28:41

回答

1

你可以這樣寫:

private void button5_Click(object sender, EventArgs e) 
{ 
    xml = new XmlDocument(); 
    xml.Load("D:\\connections.xml"); 
    StringBuilder sb = new StringBuilder(); 
    XmlNodeList xnList = xml.SelectNodes("/instruction"); 
    foreach (XmlNode xn in xnList) 
    { 
     sb.AppendLine(xn.Attribute["name"].Value); 
     foreach(XmlNode subNodes in xn.SelectNodes("destination/connection") { 
      sb.AppendLine(subNodes.InnerText); 
     } 
    } 
    textBox1.Text=sb.ToString(); 
}  

不過,我認爲這是一個非常簡單的情況下你可以解決你自己。這裏沒有技術挑戰。我建議你接受培訓,閱讀一本書並深入文檔。

PS:沒有使用StringBuilder而不是字符串連接...

+0

感謝您的回覆。一個小的更正,在內部foreach循環中應該是subNodes.InnerText而不是subNodes.Text – Gokul 2011-06-17 07:01:09

+0

相應地更新。謝謝 – 2011-06-17 07:03:30

2

嘗試這樣的:

xml = new XmlDocument(); 
    xml.Load("D:\\connections.xml"); 
    string val=""; 
    string text = ""; 
    foreach (XmlNode child in xml.DocumentElement.ChildNodes) 
     { 
      if (child.NodeType == XmlNodeType.Element) 
      { 
       //MessageBox.Show(child.Name + ": " + child.InnerText.ToString()); 
       node = child.Name; //here you will get node name 
       if (node.Equals("Instruction")) 
       { 
        val = child.InnerText.ToString(); //value of the node 
        //MessageBox.Show(node + ": " + val); 
       } 
      } 
     } 
1

這樣的事情,與內環:

 XmlNodeList xnList = xml.SelectNodes("/instruction"); 
     foreach (XmlElement xn in xnList) 
     { 
      text += "Instruction Name : " + xn.GetAttribute("name") + Environment.NewLine + Environment.NewLine; 
      foreach (XmlElement cn in xn.SelectNodes("connection")) 
      { 
       text += "Connection : " + xn.InnerText + Environment.NewLine + Environment.NewLine; 
      } 
     }