问题
I wish to access some specific attribute (Tag name) i an XML file, and place them in a list but i cant get i right. What am I doing wrong??
The list should look like this:
Tag_1
Tag_2
Tag_3
Code:
XElement xelement = XElement.Load("C:/...../Desktop/Testxml.xml");
var tagNames = from tag in xelement.Elements("tagGroup")
select tag.Attribute("name").Value;
foreach (XElement xEle in tagNames)
{
//....
}
Here is the XML file:
<configuration>
<logGroup>
<group name="cpm Log 1h 1y Avg" logInterval="* 1 * * * ?" />
<group name="cpm Log 1d 2y Avg" logInterval="* 10 * * * ?" />
</logGroup>
<tagGroup>
<tag name="Tag_1">
<property name="VALUE">
<logGroup name="cpm Log 1h 1y Avg" />
<logGroup name="cpm Log 1d 2y Avg" />
</property>
</tag>
<tag name="Tag_2">
<property name="VALUE">
<logGroup name="cpm Log 1h 1y Avg" />
<logGroup name="cpm Log 1d 2y Avg" />
</property>
</tag>
<tag name="Tag_3">
<property name="VALUE">
<logGroup name="cpm Log 1h 1y Avg" />
<logGroup name="cpm Log 1d 2y Avg" />
</property>
</tag>
</tagGroup>
</configuration>
回答1:
just change your linq query for:
var tagNames = from tag in xelement.Elements("tagGroup").Elements("tag")
select tag.Attribute("name").Value;
then tagName is an IEnumerable<string> and you can iterating like this:
foreach (var element in tagNames)
{
//element is a string
}
回答2:
Your code enumerates through the elements called tagGroup, and then attempts to get the attribute in called name. There is no attribute in tagGroup. In fact tagGroup has descendants two levels deep called logGroup. It's logGroup that has the name attribute.
This code will not work:
XElement xelement = XElement.Load("C:/...../Desktop/Testxml.xml");
var tagNames = from tag in xelement.Elements("tagGroup")
select tag.Attribute("name").Value;
What you need is something like
var tagGroups = xelement.Descendants("tag").Select(x => x.Attribute("name")).ToList();
Or if you want to the others:
var tagGroups = xelement.Descendants("logGroup").Select(x => x.Attribute("name")).ToList();
var tagGroups = xelement.Elements("tagGroup").ToList();
var logGroups = tagGroups.SelectMany (g => g.Descendants("logGroup")).ToList();
var logAttributes = tagGroups.SelectMany (g => g.Descendants("logGroup").Select(x => x.Attribute("name"))).ToList();
回答3:
Something Like :
var tagNames = xe.Element("tagGroup").Elements("tag").Select(a => a.Attribute("name").Value);
foreach (var xEle in tagNames)
{
Console.WriteLine(xEle);
}
回答4:
Try this...
var tagNames = from tag in xelement.Elements("tagGroup").Elements("tag")
select tag.Attribute("name").Value;
or
var tagNames = xelement.Elements("tagGroup")
.Elements("tag")
.Attribute("name").Value;
来源:https://stackoverflow.com/questions/26104412/how-to-access-a-specific-attribute-using-linq-to-xml