C# 从xml中提取属性

C# 从xml中提取属性,c#,.net,xml,linq,C#,.net,Xml,Linq,我需要从xml中选择属性。以下是xml: <?xml version="1.0" encoding="utf-8"?> <Examine> <Categories> <name text="test"/> <name test="test2"/> <name text="test3"/> <name text="test4"/> </Categories> &l

我需要从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>

以下是代码,请参阅以下文章:

公共类XmlValue
{
public System.Xml.Linq.XElement元素{get;set;}
公共字符串文本
{
得到
{
if(Element==null)返回null;
返回元素。值;
}
}
}
公共类XmlParser
{
公共列表Getxml()
{
XDocument xdoc=XDocument.Load(@“D:\Web Utf-8 Converter\Categories.xml”);
var list=xdoc.substands(“Categories”).SelectMany(p=>p.Elements(“name”)).Select(e=>newxmlvalue{Element=e}).ToList();
var listing=list.ToList();
返回列表;
}
}

如何获取上述xml中的值Test、test2、test3、test4?

使用
XElement.XAttribute(string)
方法获取特定属性,然后可以将其强制转换为
string
或使用
.value
属性获取其值:

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

使用
XElement.XAttribute(string)
方法获取特定属性,然后可以将其强制转换为
string
或使用
.Value
属性获取其值:

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

我收到一个错误:无法将类型“System.Collections.Generic.List”隐式转换为“System.Collections.Generic.List”@user726720如果要返回XmlValues列表,请选择XmlValues。顺便说一句,.Attribute方法返回的是XAttribute而不是XElement。我向您展示了如何获取属性的值,其余的应该没有那么难。很抱歉,我是linq方面的新手,您能用一个例子来说明这一点吗。谢谢我试过这个:Select(e=>(XmlValue)e.Attribute(“text”)),但是它给了我一个错误
Select(e=>newxmlvalue{Element=e.Attribute(“text”))
仅当您将
元素的类型更改为
XAttribute
时,此操作才有效。我收到一个错误:无法将类型“System.Collections.Generic.List”隐式转换为“System.Collections.Generic.List”@user726720如果您想返回XmlValues列表,请选择XmlValues。顺便说一句,.Attribute方法返回的是XAttribute而不是XElement。我向您展示了如何获取属性的值,其余的应该没有那么难。很抱歉,我是linq方面的新手,您能用一个例子来说明这一点吗。谢谢我试过这个:Select(e=>(XmlValue)e.Attribute(“text”)),但它给了我一个错误
Select(e=>newxmlvalue{Element=e.Attribute(“text”)
只有当您将
元素的类型更改为
XAttribute