Reputation: 565
i made a program where i retrieve xml code from my database SQL 2005, now i want to display all attribues along with thier values in windows form application. is there any function supports that?? and how?
<Permission>
<CP name="Student">
<tab name="studentinfo">
</tab>
<tab name="notes">
<groupbox name="ss">
<field type="textArea" x="xxx" />
</groupbox>
</tab>
</CP>
<CP name="Teacher">
</CP>
<CP name="doctor">
</CP>
</Permission>
output: name="Student" name="Student info"
and so on..
Upvotes: 0
Views: 531
Reputation: 3166
The XML to LINQ libraries make this pretty easy
using (XmlTextReader reader = new XmlTextReader("C:/whatever.xml"))
{
reader.Read();
XElement permission = (XElement)XElement.ReadFrom(reader);
string name = permission.Element("CP").Attribute("name").Value;
foreach (var tab in permission.Element("CP").Elements("tab"))
{
string tabName = tab.Attribute("name").Value;
}
}
Upvotes: 0
Reputation: 22555
You can do this by XML to Linq as bellow:
XDocument xmlDoc = XDocument.Load("a.xml");
var nodeAttrs = xmlDoc.Descendants().Select(x => x.Attributes());
foreach (var attrs in nodeAttrs)
{
foreach (var attr in attrs)
Console.WriteLine("Name: {0}, Value :{1}", attr.Name ,attr.Value);
}
output is as bellow for your XML:
Name: name, Value :Student
Name: name, Value :studentinfo
Name: name, Value :notes
Name: name, Value :ss
Name: type, Value :textArea
Name: x, Value :xxx
Name: name, Value :Teacher
Name: name, Value :doctor
Edit: And if you have a string which represents your XML you can do
var xmlString = "<Permission> <CP name=\"Student\"> <tab name=\"studentinfo\"></tab><tab name=\"notes\"><groupbox name=\"ss\"><field type=\"textArea\" x=\"xxx\" /></groupbox></tab></CP><CP name=\"Teacher\"></CP><CP name=\"doctor\"></CP></Permission>";
byte[] byteArray = Encoding.ASCII.GetBytes( xmlString );
MemoryStream stream = new MemoryStream( byteArray);
and then
var xmlDoc = XDocument.Load(stream);
Upvotes: 1