Reputation:
Basically I have the xml file format likes:
<?xml version="1.0" encoding="utf-8" ?>
<retentions>
<client id="1544">
<facility id="5436">
<retention period="23" />
</facility>
</client>
<client id="7353">
<facility id="3450">
<retention period="3" />
</facility>
</client>
</retentions>
I want to get all values of all attributes such as "1554", "5436", "23" etc.
Please use XDocument instead of XMLDocument. My code is wrong:
XDocument XDoc = XDocument.Load("my.xml");
IEnumerable<XElement> results = (from el in XDoc.Root.Elements("retentions")
select el);
UPDATE:(Using dictionary)
var g = from element in XDoc.Descendants("client")
from ID in element.Attributes("id")
from Facility in element.Attributes("facility")
from Period in element.Attributes("period")
select new { Key = ID.Value, Value = Period.Value };
Upvotes: 0
Views: 3826
Reputation: 13022
To get the attributes of an element:
XElement xElement;
IEnumerable attributes = xElement.Attributes();
to get all the elements of a document:
XDocument xDocument;
IEnumerable<XElement> elements = xDocument.Descendants();
Then, using LINQ: All the values are:
from element in xDocument.Descendants()
from attribute in element.Attributes()
select attribute.Value;
Is this what you want?
var dictionary = xDocument.Descendants("client").ToDictionary(element => element, element =>
(from descendant in element.Descendants() // Gets descendant elements of element
from attribute in descendant.Attributes() // Gets all the attributes of the descendant
select attribute.Value).ToList());
var g = XDoc.Descendants("client")
.ToDictionary(element => element.Attribute("id").Value,
element => new
{
element.Descendants("facility").First().Attribute("id").Value,
element.Descendants("retention").First().Attribute("period").Value
});
Upvotes: 2
Reputation: 236218
One line to get all attributes from xml document:
var attributes = ((IEnumerable)xdoc.XPathEvaluate("//@*"))
.Cast<XAttribute>().Select(a => (string)a);
UPDATE (dictionary of all nodes attributes)
var attributes = xdoc.Descendants()
.GroupBy(e => e.Name)
.ToDictionary(g => g.Key.LocalName,
g => g.SelectMany(x => x.Attributes())
.Select(a => (string)a)
.ToList());
List<string> attributesOfClient = attributes["client"];
Upvotes: 4