0

I want to iterate through all attributes from all given tags in an XML file with C# like in this example.

<TAG1 Attribute1="1234" Attribute2="1234" Attribute3="1234">
      <TAG2 xpq="123" abc="000" lkj="123"/>
</TAG1>

The XML is very long and the tags and attribute naming can change. So I must find a way to iterate through them with unknown naming. I have tested it with

XmlTextReader reader = new XmlTextReader("C:\\PathToXml\File.xml");
var optionTitle = reader.Name;                           
var AttributeName = reader.LocalName;
var AttributeValue = reader.GetAttribute(AttributeName);
var itemValue = new ListViewItem(new[] { optionTitle, AttributeName, AttributeValue });
listView1.Items.Add(itemValue);

But I only get the tag names and nothing else...

Does anyone have an idea for me?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
HansDampf
  • 9
  • 3
  • Duplicate shows XmlReader solution or if you are fine with LINQ-to-XML - duplicate of http://stackoverflow.com/questions/6253565/loop-through-all-the-attributes-of-a-node-using-xdocument. – Alexei Levenkov Jan 05 '17 at 16:26

3 Answers3

1

I prefer using Linq2Xml

var xDoc = XDocument.Load(filename);
foreach(var attr in xDoc.Descendants("TAG1").First().Attributes())
{
    Console.WriteLine(attr.Name + " " + attr.Value);
}
L.B
  • 114,136
  • 19
  • 178
  • 224
0

You should use the XDocument class, which provides a much simpler access to XML documents.

var doc = XDocument.Load("C:\\PathToXml\File.xml");
foreach(var el in doc.Descendants())
   foreach(var attr in el.Attributes())
   {
        var itemValue = new ListViewItem(new[] { el.TagName, attr.Name, attr.Value });
        listView1.Items.Add(itemValue);
   }
0

You should use XDocument to load your xml file. Then get all the attributes by using XElement.Attributes like this

var document = XDocument.Load("C:\\PathToXml\File.xml");
foreach (var attribute in document.Root.Attributes)
{
    //process the attribute
    //attribute.Name
    //attribute.Value
}
Kim Hoang
  • 1,338
  • 9
  • 24