'How do I acess Node Attribute and Node values in XML using C#

I have a XML file and it goes as below and trying to bring out the Node Attribute value from Node Value

How to use XML Deserializer to access the nodes and its values

<Roots>
    <Root id="XYZ">
                
        <Select val = "SELECT0">
            <Pin val = "00"> A </Pin>
            <Pin val = "01"> B </Pin>
            <Pin val = "02"> C </Pin>
            <Pin val = "03"> D </Pin>

        </Select>

        <Select val = "SELECT1">
            <Pin val = "00"> E </Pin>
            <Pin val = "01"> F </Pin>
            <Pin val = "02"> G </Pin>
            <Pin val = "03"> H </Pin>

        </Select>
    </Root>
</Roots>


Solution 1:[1]

I think your Xml file content is not correct, eg

        <Select val = "SELECT0">
        <Pin> val = 00> value0 </Pin>

what is following?

val = 00> value0

You can try serialize/deserialize your xml file to POCO classes by some framework, eg visit : https://github.com/ExtendedXmlSerializer/home

Following are some advises:

  1. Create a Roots class which only contain a Root class as a property.
  2. The Root class should has:
    • a property id, which should mapping to the xml attribute id.
    • a property of Selector class.
    • a collection property of Select class, eg. List<Select>;
  3. The Selector class should has a collection property List<Register>, and class Register should has properties mapping to attribute name and value;
  4. The Select class should has a property mapping to attribute val, and a collection property List<Pin>.
  5. The Pin class should has a property mapping to attribute val, and another property mapping to value.

Here is some POCO codes:

    public class Roots
    {
        public Root root { get; set; }
    }

    public class Root
    {
        public Selector selector { get; set; }
        public List<Select> selects { get; set; }
    }

    public class Selector
    {
        public List<Register> Registers { get; set; }
    }

    public class Register
    {
        public string name { get; set; }
        public string value { get; set; }
    }

    public class Select
    {
        public string val { get; set; }
        public List<Pin> Pins { get; set; }
    }

    public class Pin
    {
        public string val { get; set; }
        public string value { get; set; }
    }

Highly recommend using good naming, maybe this help : https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/naming-guidelines

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bob