我需要從深度較淺的XML中的許多節點獲取值。多級XML ForEach WPF
有效的XML樣品
<?xml version="1.0" encoding="UTF-8"?>
<server>
<id>245723</id>
<name>Server Name</name>
<host>IP Address</host>
<port>Port</port>
<servertype>
<type>Linux</type>
<cpu>Linux</cpu>
<connections>
<connection>
<id>1234</id>
<con_type>new</con_type>
</connection>
<connection>
<id>565665</id>
<con_type>new</con_type>
</connection>
<connection>
<id>908546546466</id>
<con_type>old</con_type>
</connection>
</connections>
</servertype>
</server>
所以基本上我需要通過foreach
的連接節點內訪問和運行。我已經使用下面的代碼來獲取第一級節點值(每個節點)爲listbox
。效果很好。
讀取XML
string urlAddress = "url to xml file on server";
XDocument itemz = XDocument.Load(urlAddress);
foreach (var item in itemz.Descendants("server"))
{
string name = item.Element("id").Value;
//adding value to a listbox (sample)
lstBox.Items.Add(txtBoxName.Content = item.Element("id").Value);
}
C#代碼是沒有使用相同的代碼(這樣)下的連接節點來獲得每個項目(值)的方式。因此,像下面
server> servertype > connections > foreach connection > get values of connection
流例如它需要像
foreach (var item in itemz.Descendants("server")) {
foreach (var item in itemz.Descendants("connections")) {
//foreach connection
foreach (var item in itemz.Descendants("connection")) {
//add connection id to listbox
lstBox.Items.Add(txtBoxName.Content = item.Element("id").Value);
}
}
}
********** **********編輯
使用以下代碼將多個值提取到列表框輸出
//foreach connection inside connections
//connection node inner node values
string id = item.Element("id").Value);
string type = item.Element("type").Value);
string other = item.Element("other").Value);
string etc = item.Element("etc").Value);
lstBox.Items.Add(txtBoxName.Content = id + type + other + etc;
你能否更清楚你的預期產出。您的最後一個示例將簡單地將屬於「連接」節點的所有「id」元素值放入列表中。那是你想要達到的目標嗎?或者你有每個服務器的列表?或者是其他東西? – Alex
基本上在連接節點下面有多個連接節點,其中有節點(id,類型等),它們具有im試圖輸出到每個連接節點的列表框的值。編輯問題以及如何將每個項目添加到listbox – BENN1TH
@Alex的建議爲我工作。 – BENN1TH