Click here to Skip to main content
15,891,253 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
XML
<?xml version="1.0"?>
<Test>
    <Test a="1" b="2" c="3"/>
<Test>



i want to read a,b,c and print values. but without mention any attribute name.i need some common method.(using linq)
Posted
Comments

C#
var xml ="<?xml version=\"1.0\"?>\r\n<root>\r\n    <Test a=\"1\" b=\"2\" c=\"3\"/>\r\n</root>";
XDocument doc = XDocument.Parse(xml);
var attributes = doc.Descendants("Test").SelectMany(x=> x.Attributes())
.Select(a=>new{Name =a.Name, Value=a.Value});

result:
Name Value 
a    1 
b    2 
c    3 

UPDATE:
======

if you don't need to specify any element names in the code, just use Descendants()
C#
var attributes = doc.Descendants().SelectMany(x=> x.Attributes())
.Select(a=>new{Name =a.Name, Value=a.Value});
 
Share this answer
 
v2
Comments
tnkarthi 5-Aug-15 6:59am    
thanks. i exactly want this output. but i need it without mention "Test". That is doc.Descendants("Test"). in my scenario i cant put "Test" .
Maciej Los 5-Aug-15 8:23am    
5ed!

It's quite simple and has been clearly explained here: How to: Retrieve a Collection of Attributes (LINQ to XML)[^]


Accordingly to your example:


C#
string xcontent = @"<?xml version='1.0'?>
<Root>
    <Test a='1' b='2' c='3'/>
</Root>";
XDocument xdoc = XDocument.Parse(xcontent);
var result = xdoc
    .Descendants()
    .Attributes()
    .Select(x=>new{Name = x.Name, Value = x.Value});
Console.WriteLine("Name | Value");
foreach(var n in result)
{
    Console.WriteLine("{0} | {1}", n.Name, n.Value);
}
 
Share this answer
 
v2
Comments
tnkarthi 5-Aug-15 6:59am    
thanks. i exactly want this output. but i need it without mention "Test". That is doc.Descendants("Test"). in my scenario i cant put "Test" .
Maciej Los 5-Aug-15 7:02am    
So, remove "Test" from Descendants(). See updated answer.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900