0

I need to pick the attributes from the xml. Here is the xml:

<?xml version="1.0" encoding="utf-8"?>
<Examine>
  <Categories>
    <name text="test"/>
    <name test="test2"/>
    <name text="test3"/>
    <name text="test4"/>
  </Categories>
</Examine>

Here's the code, with help from the followin post: Cannot implicitly convert type system.colllections.generic

 public class XmlValue
{
    public System.Xml.Linq.XElement Element { get; set; }


    public string Text
    {
        get
        {
            if (Element == null) return null;
            return Element.Value;
        }
    }
}

public class XmlParser
{
    public List<XmlValue> Getxml()
    {
        XDocument xdoc = XDocument.Load(@"D:\Web Utf-8 Converter\Categories.xml");

        var list = xdoc.Descendants("Categories").SelectMany(p => p.Elements("name")).Select(e => new XmlValue {Element = e}).ToList();

        var listing = list.ToList();
        return listing;
    }
}

How do I get the value Test,test2, test3,test4 as in the xml above?

Community
  • 1
  • 1
user726720
  • 1,127
  • 7
  • 25
  • 59

1 Answers1

6

Use XElement.XAttribute(string) method to get a particular attribute and then you can cast it to string or use .Value property to get it's value:

var list = xdoc.Descendants("Categories")
    .SelectMany(p => p.Elements("name"))
    .Select(e => (string)e.Attribute("text"))
    .ToList();
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
  • I'm getting an error: Cannot implicitly convert type 'System.Collections.Generic.List' to 'System.Collections.Generic.List' – user726720 Oct 01 '14 at 08:40
  • @user726720 if you want to return a list of XmlValues then Select XmlValues. BTW, .Attribute method returns an XAttribute not an XElement.I showed you how to get Attribute's value, the rest shouldn't be that hard. – Selman Genç Oct 01 '14 at 08:44
  • I'm sorry I'm new to the linq stuff, can you show that with an example. THank you – user726720 Oct 01 '14 at 08:56
  • I tried this: Select(e=> (XmlValue)e.Attribute("text")), yet it's giving me an error – user726720 Oct 01 '14 at 09:01
  • 1
    `Select(e=> new XmlValue { Element = e.Attribute("text") })` This will only work if you change type of `Element` to `XAttribute` – Selman Genç Oct 01 '14 at 09:20