Sar*_*edi 8 c# xml linq linq-to-xml
我有一个自定义配置文件.
<Students>
<student>
<Detail Name="abc" Class="1st Year">
<add key="Main" value="web"/>
<add key="Optional" value="database"/>
</Detail>
</student>
</Students>
Run Code Online (Sandbox Code Playgroud)
我通过IConfigurationHandler接口实现读取了这个文件.当我读取Detail元素的childNode属性时.它将结果返回到IDE的立即窗口.
elem.Attributes.ToObjectArray()
{object[2]}
[0]: {Attribute, Name="key", Value="Main"}
[1]: {Attribute, Name="value", Value="web"}
Run Code Online (Sandbox Code Playgroud)
当我尝试在Console上写字时
Console.WriteLine("Value '{0}'",elem.Attributes.ToObjectArray());
Run Code Online (Sandbox Code Playgroud)
它确实让我回报
Value : 'System.Configuration.ConfigXmlAttribute'
Run Code Online (Sandbox Code Playgroud)
elem.Attributes.Item(1)
方法给出了Name和Value的详细信息,但在这里我需要传递我当前不知道的属性的索引值.
我希望通过LINQ查询获取属性的名称和值,并在Console上为每个childNode属性显示,如下所示:
Value : Name="Key" and Value="Main"
Name="value", Value="web"
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?
如果您想使用此Xml 库,您可以使用以下代码获取所有学生及其详细信息:
XElement root = XElement.Load(file); // or .Parse(string)
var students = root.Elements("student").Select(s => new
{
Name = s.Get("Detail/Name", string.Empty),
Class = s.Get("Detail/Class", string.Empty),
Items = s.GetElements("Detail/add").Select(add => new
{
Key = add.Get("key", string.Empty),
Value = add.Get("value", string.Empty)
}).ToArray()
}).ToArray();
Run Code Online (Sandbox Code Playgroud)
然后迭代它们使用:
foreach(var student in students)
{
Console.WriteLine(string.Format("{0}: {1}", student.Name, student.Class));
foreach(var item in student.Items)
Console.WriteLine(string.Format(" Key: {0}, Value: {1}", item.Key, item.Value));
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5605 次 |
最近记录: |