简体   繁体   中英

Picking attributes from xml

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?

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM