使用LINQ到XML
string name = "Brian";
XDocument doc = XDocument.Load(yourXmlFile);
var matches = doc.Root
.Descendants("Option")
.Where(option => name.StartsWith(option.Element("NameStartsWith").Value))
.Select(option => option.Element("Data").Value);
foreach(var data in matches)
{
Console.WriteLine("The Answer is: {data}");
}
XContainer.Descendants Method (XName)將返回作爲參數傳遞從當前的XElement的所有層次級別名稱的所有元素。
如果元素NameStartsWith
在Option
內是可選的,那麼只需在LINQ
方法的鏈中添加檢查null。如果不存在這樣的元素,則XElement.Element(XName name)
將返回null
。
var matches = doc.Root
.Descendants("Option")
.Where(option => option.Element("NameStartsWith") != null)
.Where(option => name.StartsWith(option.Element("NameStartsWith").Value))
.Select(option => option.Element("Data").Value);
如果Option
元件包含需要被選擇的一個以上的其它元素,則創建它們代表所有需要的數據的類和填充它裏面Select
方法
public class Option
{
public string NameStartsWith {get; set; }
public string Data {get; set; }
public string ElementOne {get; set; }
public string ElementTwo {get; set; }
}
var matches = doc.Root
.Descendants("Option")
.Where(option => option.Element("NameStartsWith") != null)
.Where(option => name.StartsWith(option.Element("NameStartsWith").Value))
.Select(option => new Option
{
NameStartsWith = option.Element("Data").Value,
Data = option.Element("Data").Value,
ElementOne = option.Element("ElementOne").Value,
ElementTwo = option.Element("ElementTwo").Value,
});
當然,你可以使用匿名而不是創建一個。
感謝,它運作良好,除了一個問題。有時在每個「
@JamesNapier - 檢查更新的答案 – Fabio
@JamesNapier這是使用xpath的優勢。它爲你做所有這些檢查...... –