9
9
using System . Windows . Forms ;
10
10
using System . Xml ;
11
11
using System . Linq ;
12
+ using System . Xml . Linq ;
12
13
13
14
namespace _02_XML
14
15
{
15
16
public partial class MainWindow : Form
16
17
{
17
- private XmlDocument xDoc = new XmlDocument ( ) ;
18
- private XmlElement xRoot ;
18
+ private XElement gems ;
19
19
20
20
private void LoadColors ( )
21
21
{
22
- // Load colors
23
-
24
22
HashSet < string > gemsColors = new HashSet < string > ( ) ;
25
23
26
24
gemsColors . Add ( "" ) ;
27
25
28
- XmlElement xRoot = xDoc . DocumentElement ;
29
- foreach ( XmlNode xnode in xRoot )
30
- {
31
- var gemSpecs = new List < string > ( ) ;
32
-
33
- foreach ( XmlNode childnode in xnode . ChildNodes )
34
- {
35
- if ( childnode . Name == "color" )
36
- {
37
- gemsColors . Add ( childnode . InnerText ) ;
38
- }
39
-
40
- gemSpecs . Add ( childnode . InnerText ) ;
41
- }
26
+ IEnumerable < XElement > allGemsColors = from item in gems . Elements ( )
27
+ select item . Element ( "color" ) ;
42
28
43
- gemsView . Rows . Add ( gemSpecs . ToArray ( ) ) ;
29
+ foreach ( string color in allGemsColors )
30
+ {
31
+ gemsColors . Add ( color ) ;
44
32
}
45
33
46
- gemsColor . DataSource = gemsColors . ToList ( ) ;
34
+ gemsColor . DataSource = gemsColors . ToArray ( ) ;
47
35
}
48
36
49
37
private void LoadGemsByColor ( string color )
50
38
{
51
39
gemsView . Rows . Clear ( ) ;
52
40
53
- foreach ( XmlNode xnode in xRoot )
41
+ IEnumerable < XElement > gemsByColor = from item in gems . Elements ( )
42
+ where ( string ) item . Element ( "color" ) == color
43
+ select item ;
44
+
45
+ foreach ( var gem in gemsByColor )
54
46
{
55
- bool rightColor = color == "" ? true : false ;
56
- var gemSpecs = new List < string > ( ) ;
57
-
58
- foreach ( XmlNode childnode in xnode . ChildNodes )
59
- {
60
- if ( childnode . Name == "color" )
61
- {
62
- if ( childnode . InnerText == color )
63
- {
64
- rightColor = true ;
65
- }
66
- }
67
-
68
- gemSpecs . Add ( childnode . InnerText ) ;
69
- }
70
-
71
- if ( rightColor )
72
- {
73
- gemsView . Rows . Add ( gemSpecs . ToArray ( ) ) ;
74
- }
47
+ IEnumerable < string > gemSpecs = from item in gem . Elements ( )
48
+ select item . Value ;
49
+
50
+ gemsView . Rows . Add ( gemSpecs . ToArray ( ) ) ;
75
51
}
76
52
}
77
53
@@ -81,8 +57,11 @@ public MainWindow()
81
57
82
58
// Load XML
83
59
84
- xDoc . Load ( Path . Combine ( Application . StartupPath . ToString ( ) , "./Gems.xml" ) ) ;
85
- xRoot = xDoc . DocumentElement ;
60
+ var filename = "Gems.xml" ;
61
+ var currentDirectory = Directory . GetCurrentDirectory ( ) ;
62
+ var gemsFile = Path . Combine ( currentDirectory , filename ) ;
63
+
64
+ gems = XElement . Load ( gemsFile ) ;
86
65
87
66
// Load colors
88
67
0 commit comments