简体   繁体   English

从xml中选取属性

[英]Picking attributes from xml

I need to pick the attributes from the xml. 我需要从xml中选择属性。 Here is the xml: 这是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 这是代码,在后续文章的帮助下: 无法隐式转换类型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? 如何获得上述xml中的值Test,test2,test3,test4?

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: 使用XElement.XAttribute(string)方法获取特定属性,然后可以将其.Valuestring或使用.Value属性获取其值:

var list = xdoc.Descendants("Categories")
    .SelectMany(p => p.Elements("name"))
    .Select(e => (string)e.Attribute("text"))
    .ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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