Linq to XML get attribute

Post 13 of 21

Linq to XML simple get attribute from node statement
up vote
2
down vote
favorite
Ok so heres the code snippet.

XDocument themes = XDocument.Load(HttpContext.Current.Server.MapPath(“~/Models/Themes.xml”));
string result = “”;
var childType = from t in themes.Descendants()
where t.Attribute(“name”).Value.Equals(theme)
select new { value = t.Attribute(“type”).Value };

foreach (var t in childType) {
result += t.value;
}
return result;
and heres the xml

<?xml version=”1.0″ encoding=”utf-8″ ?>
<themes>
<theme name=”Agile”>
<root type=”Project”>
<node type=”Iteration” >
<node type=”Story”>
<node type=”Task”/>
</node>
</node>
</root>
</theme>
<theme name=”Release” >
<root type=”Project”>
<node type=”Release”>
<node type=”Task” />
<node type=”Defect” />
</node>
</root>
</theme>
</themes>
what am I doing wrong? I keep getting an object not set to an instance of an object exception.

—-edit—–

ok let me add abit more, what I’m trying to return is the type of the selected node based on the type of a parent node, IE, if the theme is “Agile” and the parent node is “Project” then the return value should be “Iteration”. Thats the final outcome but I never got that far because I got stuck with what you see above.

c# linq-to-xml
share|improve this question
edited 5 hours ago

Aerospace
406311
asked Oct 21 ’10 at 12:06

Morgeh
1992617

I edited my answer to get in line with your added informations. – Alex Bagnolini Oct 21 ’10 at 17:57
add comment
4 Answers
activeoldestvotes
up vote
3
down vote
accepted
I think you want something closer to this:

XDocument themes = XDocument.Load(HttpContext.Current.Server.MapPath(“~/Models/Themes.xml”));
string result = “”;
var childType = from t in themes.Descendants(“theme”)
where t.Attribute(“name”).Value.Equals(theme)
select new { value = t.Descendants().Attribute(“type”).Value };

foreach (var t in childType) {
result += t.value;
}
return result;
EDIT: Based on your additional info, perhaps this is even closer:

XDocument themes = XDocument.Load(HttpContext.Current.Server.MapPath(“~/Models/Themes.xml”));
string result = “”;
var childType = from t in themes.Descendants(“theme”)
where t.Attribute(“name”).Value.Equals(theme)
where t.Element(“node”).Attribute(“type”).Value == parent
select new { value = t.Descendants().Attribute(“type”).Value };

foreach (var t in childType) {
result += t.value;
}
return result;

,

This article was written by admin

Menu