![](/img/trans.png)
[英]WinForms, DataGridView: Filtering XML data using attributes from multiple nodes
[英]XML multiple nodes into dataGridView with 2 column
我試圖將此 xml 放入DataGridView
,數據網格視圖僅顯示節點和值。
我曾嘗試使用switch
、 case
、 foreach
節點,但結果節點和值僅顯示在 1 列而不是 2 列上。 我嘗試使用選擇單個節點,但它顯示對象錯誤。,
下面是代碼示例:
try
{
reader = new XmlTextReader(filename);
reader.WhitespaceHandling = WhitespaceHandling.None;
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
//dataGridView1.Rows[cnt].Cells[1].Value = reader.Name;
dataGridView1.Rows.Add(reader.Name);
break;
case XmlNodeType.Text:
dataGridView1.Rows.Add("\t",reader.Value);
//dataGridView1.Rows[cnt].Cells[0].Value = reader.Value;
break;
case XmlNodeType.EndElement:
break;
}
我的導師說,使用此代碼,但我不知道我的導師示例缺少什么
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("ConfigAPI.xml");
XmlNodeList nodeList = xmlDoc.DocumentElement.SelectNodes("/ConfigAPI");
foreach (XmlNode node in nodeList)
{
node.SelectSingleNode("UIPlayer").InnerText;
}
這里還有一個 XML 的例子
<ConfigAPI>
<CoreUIAddress>http://localhost:3223</CoreUIAddress>
<CoreAppsAddress>http://localhost:3333</CoreAppsAddress>
<CoreCustomPrinterAddress>http://localhost:3001</CoreCustomPrinterAddress>
<CorePassbookPrinterAddress>http://localhost:3002</CorePassbookPrinterAddress>
<CorePrinterAddress>http://localhost:3003</CorePrinterAddress>
<CoreEDCAddress>http://localhost:3010</CoreEDCAddress>
<CoreCamAddress>http://localhost:3011</CoreCamAddress>
<CoreUPSAddress>http://localhost:3012</CoreUPSAddress>
</ConfigAPI>
通過使用第一個代碼,它顯示了這樣的東西(沒有“\\t”)
Column 1 Column 2
core UI Adress
http localhost
core APps
http localhost
不確定如何在第 2 列上顯示數據,以便可以這樣查看
Column 1 Column 2
Core Ui Adress Http Localhost
Core APPs Http Localhost
使用發布的第二個示例中的幾行代碼和給定的 XML... 下面應該顯示兩列數據。
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(@"PathToYourXMLFile\ConfigAPI.xml");
XmlNodeList RootNodeList = xmlDoc.DocumentElement.SelectNodes("/ConfigAPI");
for (int i = 0; i < 2; i++) {
dataGridView1.Columns.Add(new DataGridViewTextBoxColumn());
}
foreach (XmlNode ConfigNode in RootNodeList[0]) {
foreach (XmlNode childNode in ConfigNode.ChildNodes) {
int newRowIndex = dataGridView1.Rows.Add();
dataGridView1.Rows[newRowIndex].Cells[0].Value = childNode.ParentNode.Name;
dataGridView1.Rows[newRowIndex].Cells[1].Value = childNode.InnerText;
}
}
添加每個 OP 評論...
從某種意義上說,第一個“外部”循環並不是真正需要使用發布的 XML,這有點令人困惑。 當我測試代碼時,我在 XML 文件中有許多ConfigAPI
節點。 不僅僅是你發布的那個。 因此,您可以將其簡化為一個循環……
foreach (XmlNode childNode in RootNodeList[0].ChildNodes) {
int newRowIndex = dataGridView1.Rows.Add();
dataGridView1.Rows[newRowIndex].Cells[0].Value = childNode.Name;
dataGridView1.Rows[newRowIndex].Cells[1].Value = childNode.InnerText;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.