J. Leeroy
J. Leeroy

Reputation: 440

C# read xml datatable in datatable

I need to read datatable in datatabele in xml file. For instance I have this xml settings:

<Devs>
    <Dev_1>
        <port>COM7</port>
        <addrs>1, 2</addrs>
        <SupplyVoltageMeasurement>
            <addr>2</addr>
            <channel>3</channel>
        </SupplyVoltageMeasurement>
    </Dev_1>
    <Dev_2>
        <port>COM6</port>
        <addrs>3, 4</addrs>
        <SupplyVoltageMeasurement>
            <addr>4</addr>
            <channel>3</channel>
        </SupplyVoltageMeasurement>
    </Dev_2>
    <Common>
        <BaudRate>38400</BaudRate>
        <BufferSize>30</BufferSize>
        <UpdatePeriod>50</UpdatePeriod>
        <SupplyVoltageChannel>3</SupplyVoltageChannel>
    </Common>
</Devs>

So I can read Dev_1 as a table, but I cannot read SupplyVoltageMeasurement as a table. So how do I read datatable SupplyVoltageMeasurement in datatable Dev_1?

Upvotes: 1

Views: 120

Answers (2)

manish
manish

Reputation: 1458

XElement xmlDoc = XElement.Load("SO-Question.xml"); // initialize your .xml document to read from
foreach (var handle in xmlDoc.Elements().Where(e => e.Name.ToString().StartsWith("Dev"))) // traverse each node of the .xml doc, based on a match condition, here : every node that starts with "Dev"
{
    // retrieve the value of every Element in the Node (mark the nestings)
    var devName = handle.Name;
    var port = handle.Element("port").Value;
    var addrs = handle.Element("addrs").Value;
    var addr = handle.Element("SupplyVoltageMeasurement").Element("addr").Value;
    var channel = handle.Element("SupplyVoltageMeasurement").Element("channel").Value;
}

Upvotes: 1

Tolga Evcimen
Tolga Evcimen

Reputation: 7352

Initialize the xml with XElement class. After that it is really easy to use.

var xml = new XElement("xmlSTringAbove");
foreach ( var dev in xml.Elements().Where(e=>e.Name.StartsWith("Dev")) )
{
    /// this line gives Dev_1, Dev_2 ...
    var devName = dev.Name;

    var addr = dev.Element("SupplyVoltageChannel").Element("addr").Value;
    var channel = dev.Element("SupplyVoltageChannel").Element("channel").Value;

    /// use addr, channel and devName as you like
}

Upvotes: 1

Related Questions