简体   繁体   中英

getting attributes and values of xml using C#

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..

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);

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;
    }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM