Read Xlement fully using LinQ
I have an XElement which I am getting after parsing an xml. This XElement needs to be read only when the need arises so, I have stored it in a list for future use.
I have to read this XElement using Linq.
XDocument doc = XDocument.Parse(DataManager.offeringElements[index].DataElem.ToString());
var docNode = from dataNode in doc.Descendants("DataLinks")
select new
{
Offering = dataNode .Element("link").Value,
linkUrl = dataNode.Element("link").Attribue("href").Value
};
the Xelement has the following nodes
<DataL开发者_JAVA百科inks>
<link href="">a. Management</link>
<link href="">b. Analytics</link>
<link href="">c. Development</link>
</DataLinks>
My problem is that I am not able to read all the three nodes.I am able to get only the first node. Where is it going wrong?
This should work i.e. Elemenets not Descendants and ensure when selecting new, you are selecting a type of object.
public class ObjectType
{
public Offering {get; set;}
public linkUrl {get; set;}
}
var docNode = from dataNode in doc.Elemenets ("DataLinks")
select new ObjectType
{
Offering = dataNode .Element("link").Value,
linkUrl = dataNode.Element("link").Attribue("href").Value
};
I would do it like this. IMHO, the method syntax looks cleaner then the query syntax. Note that this is untested code.
IEnumerable<XElement> seqLinks = doc.Descendants("DataLinks").Single()
.Descendants("link");
foreach(XElement link in seqLinks)
{
Console.WriteLine("Value is {0}, and href is {1}",
link.Value, link.Attribute("href").Value)
}
精彩评论