views:

82

answers:

2

hi all,

I know how to write to xml files, but I'm having trouble doing what I need to do and can't find adequate info on this type of problem.

Here's one xml file below:

<?xml version="1.0" encoding="utf-8"?>
<controls>
    <Label Content="Double-click to edit." Location="258, 178" Size="101, 13" ForeColor="-1" />  
    <LinkLabel Content="Double-click to edit." Location="532, 133" Size="101, 13" LinkColor="-1" />  
    <LinkLabel Content="Double-click to edit." Location="424, 212" Size="101, 13" LinkColor="-1" /> 
    <Label Content="Double-click to edit." Location="282, 89" Size="101, 13" ForeColor="-1" />  
    <Label Content="Double-click to edit." Location="528, 178" Size="101, 13" ForeColor="-1" />  
    <LinkLabel Content="Double-click to edit." Location="528, 133" Size="101, 13" LinkColor="-1" />  
    <LinkLabel Content="Double-click to edit." Location="528, 149" Size="101, 13" LinkColor="-1" /> 
    <Label Content="Double-click to edit." Location="528, 164" Size="101, 13" ForeColor="-1" />
</controls>

And what I need to do once I've opened this file in my app is:

foreach(control in XmlFile)
{   

  get Content
  get Location
  get Size
  get ForeColor/LinkColor
  // do something...
}

Can somebody please help me out with this? I'd appreciate any help at all.

Thank you

Bael

+1  A: 

If you are trying to iterate on all your controls in the XML and retreive the info, you should use XPath.

Here is an example:

XPathDocument Doc = new XPathDocument("yourfile.xml");
XPathNavigator navigator = Doc.CreateNavigator();
XPathNodeIterator iterator = navigator.Select("/controls/*");
while (iterator.MoveNext())
{
    System.Diagnostics.Debug.Print(iterator.Current.Content);
    System.Diagnostics.Debug.Print(iterator.Current.Location);
}
Am
+1  A: 

Using LINQ: (For ForeColor/LinkColor check for null)

XDocument loaded = XDocument.Load(@"C:\XMLFile1.xml");

            var q = from c in loaded.Descendants().Descendants()
                            select new
                            {
                                content = c.Attribute("Content"),
                                location = c.Attribute("Location"),
                                size = c.Attribute("Size"),
                                foreColor = c.Attribute("ForeColor"),
                                linkColor = c.Attribute("LinkColor")
                            };

            foreach (var controlItem in q)
                Console.WriteLine("Control content = {0}", controlItem.content);
Igor
+1, nice, wasn't sure how to do this in linq
Am
thank you for this it's very nicely written. How would I also get the Name of the control? e.g. Label or LinkLabel?
baeltazor
just add "name = c.Name"
Igor