Get attribute name in addition to attribute value in xml

I get dynamic xml, where I won’t know the attribute names, if you look at the xml and the code ... I tried to make a simple example, I can get the attribute values, i.e. "myName", "myNextAttribute" and "blah", but I cannot get the attribute names, that is, "name", "nextAttribute" and "etc1". Any ideas, I suppose, that this should be something easy that I’m missing ... but I’m sure that it’s not there.

    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
source share
2 answers

You can see on 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();
}
+24
source

, , if.

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

, && , , xr.NoteType , if .

0

All Articles