我是C#,Xml的初学者。如果我必须在TextBox中输入一个值(partnumber)(比如704644-B21),那么应该在XML文件中搜索partnumber,并显示它是否存在。
<Processor>
<Item>
<partnumber>678244-B21</partnumber>
<processorname> E5-2637 Kit</processorname>
<processortype>Dual Core</processortype>
<quantity>2</quantity>
</Item>
</Processor>
<Interconnects>
<Interconnect Bay="Bay1" partnumber="516733-B21">Ethernet - 6120XG Blade Switch</Interconnect>
<Interconnect Bay="Bay2" partnumber="641146-B21">Ethernet - Fabric Ext Module</Interconnect>
<Interconnect Bay="Bay3" partnumber="516733-B21">Ethernet - HP ProCurve 6120XG Blade Switch(516733-B21)</Interconnect>
<Interconnect Bay="Bay4" partnumber="658250-B21">Ethernet - XG Blade Switch</Interconnect>
<Interconnect Bay="Bay5" partnumber="658250-B21">Ethernet - XG Blade Switch</Interconnect>
<Interconnect Bay="Bay6" partnumber="438031-B21">Ethernet - BL-c Switch</Interconnect>
<Interconnect Bay="Bay7" partnumber="451438-B21">Ethernet - Cisco Catalyst Blade Switch 3120G</Interconnect>
<Interconnect Bay="Bay8" partnumber="658250-B21">Ethernet - XG Blade Switch(658250-B21</Interconnect>
</Interconnects>
</ModelDetails>
当我在文本框中输入部件号时,我想通过Messagebox知道,如果在文本框中输入的部件号存在于xml文件中。如果部件号存在,则消息框应显示“Partnumber {0] exists”,否则必须显示“部件号{0}不存在。”
private bool hasNode;
XmlDocument xworkload = new XmlDocument();
private void btnPnoCheck_Click(object sender, RoutedEventArgs e)
{
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.FileName = "Document";
dlg.DefaultExt = ".hpa";
dlg.Filter = "Xml document (.hpa)|*.hpa";
var result = dlg.ShowDialog();
if(result==true)
{
xworkload.Load(dlg.FileName);
string xmlcontents = xworkload.InnerXml;
string textToSearch = textBox1.Text;
bool hasnode = (xworkload.DocumentElement.SelectNodes("//Item/partnumber[text()='" + textToSearch + "']").Count > 0) ;
if (!hasnode)
{
MessageBox.Show(String.Format("Part number {0}{1} found ", textBox1.Text, (!hasNode ? " not" : String.Empty)));
}
else
MessageBox.Show(String.Format("Part number {0} found" , textBox1.Text));
}
}
上述代码不计算'Interconnects'标记
中的partnumber答案 0 :(得分:2)
请参阅问题:Find an element in xml by its inner text
使用以下方法搜索某个事件(按一下按钮?在textChanged上?根据您的需要):
// Load your document
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xmlFile);
string textToSearch = YourTextBox.Text;
bool hasNode = (xmlDoc.SelectNodes("/Expansion/ID[text()='" + textToSearch + "']").Count > 0);
或
bool hasNode = (xmlDoc.SelectSingleNode("/Expansion/ID[text()='" + textToSearch + "']" != null);
编辑:对于您的补充:如果您只想在未找到项目时显示消息框:
MessageBox.Show(String.Format("Item {0}{1} found", textBox1.Text, (!hasNode ? " not" : String.Empty)));
答案 1 :(得分:1)
对于实例,请在文本更改事件中使用以下标识输入的值。你可以使用Val的数量。
string xml = "";
XDocument doc = XDocument.Parse(xml);
string text = TextBox.Text;
var Val = doc.Descendants("Item").Where(txt => txt.Element("ID").Value.Equals(text));
或者下面返回布尔值
var Val = doc.Descendants("Item").Where(txt => txt.Element("ID").Value.Equals(textbox)).Any();