-4

how to deserialize the below xml : Need to read AdapterName,ConnectorIndex and ViewType

<?xml version="1.0" encoding="utf-8"?>

<MonitorConfiguration>
<System Type="1"> </System>
<Adapters>
<Adapter Name="P1" ></Adapter>
<Monitors>
<Monitor ConnectorIndex="P1" ViewType="C1"></Monitor>
<Monitor ConnectorIndex="P2" ViewType="C2"></Monitor>
<Monitor ConnectorIndex="P2" ViewType="C2"></Monitor>
<Monitor ConnectorIndex="P2" ViewType="C2"></Monitor>

</Monitors>
<Adapter Name="P2" ></Adapter>
<Monitors>
<Monitor ConnectorIndex="P4" ViewType="C3"></Monitor>
<Monitor ConnectorIndex="P5" ViewType="C5"></Monitor>
<Monitor ConnectorIndex="P6" ViewType="C6"></Monitor>
<Monitor ConnectorIndex="P7" ViewType="C7"></Monitor>
</Monitors>
</Adapters>
</MonitorConfiguration>

using Deserialize method

  • 3
    Did you try searching for the many possibilities that C# and .NET offer to read XML files? – CodeCaster Sep 07 '15 at 11:08
  • 1
    You have downvotes because you've not shown any effort to do this yourself. People here will gladly help you if you have a problem with some existing code, but will (probably) not write code to meet your requirements. – Wai Ha Lee Sep 07 '15 at 11:15

2 Answers2

0

If you need to use serialization, first of all you should have a class with the same structure as your xml file. So you'll have a class say MonitorConfiguration which have lists of Adapters, Moniters and so on...

You may find this post useful for basic understanding about xml serialization.

Once you have you xml equivalent type available, you can use XmlSerializer for creating object out of your xml.

    // De-Serializes the request into class object
    public T DeserializeXml<T>(XmlNode xmlToDesearialized)
    {
        if (xmlToDesearialized == null) throw new ArgumentNullException("xmlToDesearialized");
        T deserializedObject = default(T);
        XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));

        using (StringReader stringReader = new StringReader(xmlToDesearialized.OuterXml))
        {
            XmlTextReader xmlTextReader = new XmlTextReader(stringReader);
            deserializedObject = (T)xmlSerializer.Deserialize(xmlTextReader);
        }
        return deserializedObject;
    }
Yogi
  • 9,174
  • 2
  • 46
  • 61
0

You can try with this -

var xml = new XmlDocument();
xml.Load(new StreamReader(xml));

foreach (XmlNode x1 in xml.GetElementsByTagName("Adapter"))
{
    Console.WriteLine(x1.Attributes["Name"].Name + "::" + x1.Attributes["Name"].Value);
}

var p = xml.GetElementsByTagName("Monitors");
foreach (XmlNode x in p)
{
    foreach (XmlElement e in x)
    {
        Console.WriteLine(e.Attributes["ConnectorIndex"].Name + "::" + e.Attributes["ConnectorIndex"].Value);
        Console.WriteLine(e.Attributes["ViewType"].Name + "::" + e.Attributes["ViewType"].Value);
    }
}

But from next time on, try something before you ask a question.

Amit Kumar Ghosh
  • 3,618
  • 1
  • 20
  • 24