tags:

views:

831

answers:

2

I am receiving dynamic xml where I won't know the attribute names, if you'll look at the xml and code... I tried to make a simple example, I can get the attribute values i.e. "myName", "myNextAttribute", and "blah", but I can't get the attribute names i.e. "name", "nextAttribute", and "etc1". Any ideas, I figure it has to be something easy I'm missing...but I'm sure missing it.

    static void Main(string[] args)
    {
        string xml = "<test name=\"myName\" nextAttribute=\"myNextAttribute\" etc1=\"blah\"/>";

        TextReader sr = new StringReader(xml);

        using (XmlReader xr = XmlReader.Create(sr))
        {
            while (xr.Read())
            {
                switch (xr.NodeType)
                {
                    case XmlNodeType.Element:
                        if (xr.HasAttributes)
                        {
                            for (int i = 0; i < xr.AttributeCount; i++)
                            {
                                System.Windows.Forms.MessageBox.Show(xr.GetAttribute(i));
                            }
                        }
                        break;
                    default:
                        break;
                }
            }
        }
    }
+5  A: 

You can see in MSDN:

if (reader.HasAttributes) {
  Console.WriteLine("Attributes of <" + reader.Name + ">");
  while (reader.MoveToNextAttribute()) {
    Console.WriteLine(" {0}={1}", reader.Name, reader.Value);
  }
  // Move the reader back to the element node.
  reader.MoveToElement();
}
Dror
Thanks, I thought it had to be something close... also I found in my original for loop, I could have done xr.MoveToAttribute(i) and gotten the same affect.
Greg J
A: 

Your switch is unnecessary since you only have a single case, try rolling that into your if statement instead.

if (xr.NodeType && xr.HasAttributes)
{
    ...
}

Note that the && operator evaluates in order, so if xr.NoteType is false, the rest of the arguments are ignored and the if block is skipped.

Soviut
In this example yes, I have more cases in the 'real world' scenario, I just tried to keep it clean. Thanks though.
Greg J