有沒有更好的方法來做到這一點? 我必須得到兩個屬性值。 XML總是隻有這2個屬性。C#使用LINQ to XML讀取具有相同名稱的多個元素
我的XML:
<Template name="filename.txt">
<Property name="recordSeparator">\r\n</Property>
<Property name="fieldCount">16</Property>
</Template>
的Linq:
var property = from template in xml.Descendants("Template")
select new
{
recordDelim = template.Elements("Property").Where(prop => prop.Attribute("name").Value == "recordSeparator")
.Select(f => new { f.Value }),
fieldCount = template.Elements("Property").Where(prop => prop.Attribute("name").Value == "fieldCount")
.Select(f => new { f.Value })
};
請澄清你的問題來解釋你在做什麼。閱讀http://tinyurl.com/so-hints –
您是否期望單個模板中有多個分隔符或fieldCount屬性?因爲,Select()返回IEnumerable,在你的情況IEnumerable 。這意味着recordDelim和fieldCount都是IEnumerable 類型。那是你在匿名對象中需要的嗎? –
@kornelijepetak,xml總是相同的,只有這2個屬性。 – hs2d