-2

I have an XML file that I'm loading into an XmlDocument and need to get a list of all the attributes on nodes with a specific name.

   <shirts>
        <product ID="123" Name="tee" Serial="5678"/>
        <product ID="456" Name="crew" Serial="4566"/>
     </shirts>
    <pants>
         <product ID="123" Name="jeans" Serial="1243" Color="blue"/>
         <product ID="123" Name="dress" Serial="3455" Color="black"/>
         <product ID="123" Name="shorts" Serial="6654" Color="grey"/>
    </pants>

From this I need a list of all the "product" attributes. Result looking like:

ID
Name
Serial
Color

I don't need the values, just the attributes themselves. I'm using C# and Winforms. I know how to get the attribute values but not sure how it's done to get the attribute names themselves. How do I do that?

Blaze
  • 1,863
  • 7
  • 23
  • 40
  • What he said. Also, I'd suggest you use `XDocument` instead of `XmlDocument`, if possible. It's easier to use. – Tim S. Aug 25 '14 at 17:21
  • Simple on purpose as an example. I did not know about LINQ to XML, that's all I needed to know. I have no issue researching and learning but with no direction on even the topic to investigate it's difficult. I didn't want code. – Blaze Aug 25 '14 at 17:41

2 Answers2

2

If you are able to switch to using the System.Xml.Linq classes, you can use LINQ to XML to get what you want:

var xml = XElement.Load(xmlFileName);
var attrNames = (
    from p in xml.Descendants("product")
    from a in p.Attributes()
    select a.Name
).Distinct();
Mark
  • 8,140
  • 1
  • 14
  • 29
1

Using LinqToXml

var doc = XDocument.Load("File.xml");

var attributes = doc.Element("product").Attributes();

foreach (var item in attributes)
{
    Console.WriteLine(item.Name);
}

It takes the list of attributes from the first "product" node. if the "product" nodes have different attributes, you need collect all then distinct the list result:

var doc = XDocument.Load("File.xml");

var attributes = doc.Elements("product").SelectMany(x => x.Attributes());

var uniqAtt = attributes.Select(x => x.Name).Distinct();

foreach (var item in uniqAtt)
{
    Console.WriteLine(item);
}
dovid
  • 6,354
  • 3
  • 33
  • 73