这是我的xml文件;
<UserClass>
<Id>1</Id>
<Name>oss</Name>
<Address>
<Id>1</Id>
<Street>asstreet</Street>
</Address>
</UserClass>所以我想把这些“节点”添加到comboBox项目中。当用户键入UserClass并在“UserClass”的末尾键入“.”(点)时,Id、名称和其他内容必须列在组合框中。
用户输入了“UserClass”。和-> combobox得到这些;
UserClass.Id
UserClass.Name
UserClass.Address.Id
UserClass.Address.Street我试过很多东西,包括那一个;
...
try
{
string parsedNode = ParseComboBox();
XmlReader rdr = XmlReader.Create(new System.IO.StringReader(_globalXml));
comboBox1.Items.Clear();
while (rdr.Read())
{
if (rdr.NodeType == XmlNodeType.Element)
{
comboBox1.Items.Add(rdr.LocalName);
}
comboBox1.DroppedDown = true;
}
//string parsedNode = ParseComboBox();
//XmlNodeList childList = xml.GetElementsByTagName(parsedNode);
////comboBox1.Items.Clear();
//foreach (XmlNode node in childList)
//{
// foreach (var osman in node.ChildNodes)
// {
// comboBox1.Items.Add(parsedNode + "." + osman);
// }
//}
}
catch (Exception)
{
MessageBox.Show("fuuu");
}
}...
private string ParseComboBox()
{
string resultAsXmlNodes = null;
string text = comboBox1.Text;
if (text.EndsWith("."))
{
char[] delimiterChars = { '.' };
string[] words = text.Split(delimiterChars);
foreach (string s in words)
{
resultAsXmlNodes += s;
}
}
return resultAsXmlNodes;
}它不能正常工作。我相信有一种简单的方法可以做到。那么,最简单的方法是什么呢?或者简单地说,我如何在comboBox中显示节点名?
发布于 2012-07-27 00:23:11
我发现这有很多问题。下面是我为一个具有XML和一个ComboBox控件的form项目获得的一些示例代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
comboBox1.KeyDown += comboBox1_KeyDown;
}
private void comboBox1_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Decimal:
case Keys.OemPeriod:
LoadComboItems(comboBox1.Text);
break;
default:
break;
}
}
void LoadComboItems(string userInput)
{
comboBox1.Items.Clear();
string lookupName = userInput.Trim();
if (lookupName.Length > 0)
{
string _globalXML = Application.StartupPath + @"\XMLFile1.xml";
XmlReader rdr = XmlReader.Create(_globalXML);
while (rdr.Read())
{
if (rdr.LocalName == lookupName)
{
string ElementName = "";
int eCount = 0;
int prevDepth = 0;
while (rdr.Read())
{
if (rdr.NodeType == XmlNodeType.Element)
{
ElementName += '.' + rdr.LocalName;
eCount++;
}
else if (rdr.NodeType == XmlNodeType.EndElement && eCount == rdr.Depth)
{
if (rdr.Depth >= prevDepth)
{
comboBox1.Items.Add(lookupName + ElementName);
int pos = ElementName.LastIndexOf('.');
ElementName = ElementName.Substring(0, pos);
prevDepth = rdr.Depth;
}
eCount--;
}
}
}
}
if (rdr != null)
{
rdr.Close();
}
comboBox1.DroppedDown = true;
}
}
}
}https://stackoverflow.com/questions/11671607
复制相似问题