我想知道如何在 XML 文件中查找字符串。
假设这是我拥有的 XML 文件(顺便说一句,这些是 SQL 服务器实例,无关紧要)
<?xml version="1.0" encoding="utf-8" ?>
<Servernames>
<loc country="Lockheed">
<Servername>instance1\server1</Servername>
<Servername>instance2\server2</Servername>
<Servername>10.90</Servername>
</loc>
<loc country="SouthAmerica">
<Servername>Hide your heart</Servername>
<Servername>Bonnie Tyler</Servername>
<Servername>10.0</Servername>
</loc>
<loc country="Britian">
<Servername>Greatest\Hits</Servername>
<Servername>Dolly\Parton</Servername>
<Servername>this\is</Servername>
</loc>
</Servernames>
所以会发生什么是我从用户那里以任何格式获取一个字符串,例如我只获取实例,然后我希望列表框显示所有以 server 开头的服务器名,在上述情况下它将是
instance1\server1
instance2\serve2
等等..不知道如何实现这一点,我是否必须打开流阅读器或只是通过 xml 文件获取字符串和浏览器?
更新
private void button1_Click(object sender, RoutedEventArgs e)
{
textBox1.Clear();
string fileName = "c:\\users\\xxxx\\documents\\visual studio 2010\\Projects\\WpfApplication2\\WpfApplication2\\XML.xml";
var doc = XDocument.Load(fileName);
var findString = "Server";
var results = doc.Element("Servernames").Descendants("Servername").Where(d => d.Value.Contains(findString)).Select(d => d.Value);
listBox1.Items.Add(results.ToString());
textBox1.Text = results.ToString();
}
我只是在文本框中得到这个:System.Linq.Enumerable+WhereSelectEnumerableIterator`2[System.Xml.Linq.XElement,System.String]
强文本UPDATE2
.cs 文件代码
private void button1_Click(object sender, RoutedEventArgs e) { textBox1.Clear();
string fileName = "c:\\users\\xxxxx\\documents\\visual studio 2010\\Projects\\WpfApplication2\\WpfApplication2\\XML.xml";
var doc = XDocument.Load(fileName);
var findString = "Server";
var results = doc.Element("Servernames").Descendants("Servername").Where(d => d.Value.Contains(findString)).Select(d => d.Value);
Servers = new ObservableCollection<string>(results);
MessageBox.Show("THis is loaded");
}
XAML 看起来像这样
<ListBox Height="200" HorizontalAlignment="Left" Margin="200,44,0,0" x:Name="ListBox1" VerticalAlignment="Top" Width="237">