Как получить значение атрибута XML - C#
Формулировка задачи:
Листинг программы
- <items>
- <item name = "A">
- <element name = "el_name" address = "..."/>
- <element name = "el_name" address = "..."/>
- <element name = "el_name" address = "..."/>
- <item name = "A-1">
- <element name = "el_name" address = "..."/>
- <element name = "el_name" address = "..."/>
- <element name = "el_name" address = "..."/>
- </item>
- </item>
- <item name = "B">
- <element name = "el_name" address = "..."/>
- <element name = "el_name" address = "..."/>
- <element name = "el_name" address = "..."/>
- </item>
- </items>
Решение задачи: «Как получить значение атрибута XML»
textual
Листинг программы
- using System.Collections.Generic;
- using System.Drawing;
- using System.Linq;
- using System.Windows.Forms;
- using System.Xml.Linq;
- internal class Test
- {
- public static void Main()
- {
- var doc = XDocument.Parse(@"<items>
- <item name = 'A'>
- <element name = 'el_name' address = '...'/>
- <element name = 'el_name' address = '...'/>
- <element name = 'el_name' address = '...'/>
- <item name = 'A-1'>
- <element name = 'el_name' address = '...'/>
- <element name = 'el_name' address = '...'/>
- <element name = 'el_name' address = '...'/>
- </item>
- </item>
- <item name = 'B'>
- <element name = 'el_name' address = '...'/>
- <element name = 'el_name' address = '...'/>
- <element name = 'el_name' address = '...'/>
- </item>
- </items>");
- var root = doc.Root;
- var x = GetNodes(new TreeNode(root.Name.LocalName), root).ToArray();
- var tree = new TreeView();
- tree.Nodes.AddRange(x);
- tree.AfterSelect +=
- (sender, args) =>
- {
- var tmp = string.Join(" ", args.Node.Text.Split(' ').Skip(1));
- if (tmp != string.Empty)
- {
- MessageBox.Show(string.Format("У выбранного элемента атрибуты -> {0}", tmp));
- }
- };
- tree.Size = new Size(400, 400);
- var form = new Form { Size = new Size(500, 500) };
- form.Controls.Add(tree);
- form.AutoSize = true;
- Application.Run(form);
- }
- private static IEnumerable<TreeNode> GetNodes(TreeNode node, XElement element)
- {
- return element.HasElements
- ? node.AddRange(
- element.Elements()
- .Select(
- item =>
- new
- {
- item,
- tree =
- new TreeNode(item.Name.LocalName + " " +
- (item.HasAttributes ? string.Join(" ", item.Attributes()) : ""))
- })
- .SelectMany(@t => GetNodes(@t.tree, @t.item)))
- : new[] { node };
- }
- }
- public static class TreeNodeEx
- {
- public static IEnumerable<TreeNode> AddRange(this TreeNode collection, IEnumerable<TreeNode> nodes)
- {
- var items = nodes.ToArray();
- collection.Nodes.AddRange(items);
- return new[] { collection };
- }
- }
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д