1

I have XML in this format:

<?xml version="1.0" standalone="yes"?>
<DocumentElement>
<Session>
<bIsImages>False</bIsImages>
<bIsPlayMedia>False</bIsPlayMedia>
<bIsSubject>False</bIsSubject>
<bIsVideo>False</bIsVideo>
<dtCreDate>2012-07-23</dtCreDate>
<dtSes_Date1>2001-01-01</dtSes_Date1>
<dtSes_Date2>2001-01-01</dtSes_Date2>
<dtSes_Date3>2001-01-01</dtSes_Date3>
<nClient_ID>32</nClient_ID>
<nDelay>32</nDelay>
<nImage_ID>32</nImage_ID>
<nOperator_ID>32</nOperator_ID>
<nSession_ID>32</nSession_ID>
<nVitality>32</nVitality>
<strDescr>qi stagnatie abq</strDescr>
<strMediaPath></strMediaPath>
<strName>qi stagnatie abq</strName>
<strPrimCause></strPrimCause>
<strSubjectPath>IDF_Eric duBosc.JPG</strSubjectPath>
</Session>
<SessionProgramData>
</SessionProgramData><SessionSubProgramData>
</SessionSubProgramData><SessionTuningData>
<SessionTuning>
    <SessionTuning_ID>332</SessionTuning_ID>
    <Session_ID>33</Session_ID>
    <Tuning>Brjesh</Tuning>
    <TuningDescr>Brijesh Desc</TuningDescr>
    <TuningIsNegative>false</TuningIsNegative>
    <TuningAddInfo>33</TuningAddInfo>
    <Amp>4.8</Amp>
    <Amp2 />
    <Amp3 />
    <Amp4 />
    <Amp5 />
    <Amp6 />
    <TunFreq>Brjesh</TunFreq>
    <TunFreq2 />
    <TunFreq3 />
    <TunFreq4 />
    <TunFreq5 />
    <TunFreq6 />
    <Revision2>false</Revision2>
    <Revision3>false</Revision3>
    <Revision4>false</Revision4>
    <Revision5>false</Revision5>
    <Revision6>false</Revision6>
    <AlreadyBalanced>false</AlreadyBalanced>
    <ImagePath>E:\Live Projects with Latest Source Code\SE-5\SE-5-Latest-04March11-Multilanguage-Chinese\SE-5\bin\Release\Images\</ImagePath>
    <Amp7 />
    <TunFreq7 />
    <Revision7>0</Revision7>
    <Description>Brijesh Note</Description>
    <TunRevDate>2013-02-20T18:08:48+05:30</TunRevDate>
    <TunRevDate2>2013-02-20T18:08:48+05:30</TunRevDate2>
    <TunRevDate3>2013-02-20T18:08:48+05:30</TunRevDate3>
    <TunRevDate4>2013-02-20T18:08:48+05:30</TunRevDate4>
    <TunRevDate5>2013-02-20T18:08:48+05:30</TunRevDate5>
    <TunRevDate6>2013-02-20T18:08:48+05:30</TunRevDate6>
    <TunRevDate7>2013-02-20T18:08:48+05:30</TunRevDate7>
    <Tuning_ID>20568</Tuning_ID>
</SessionTuning>
....So on
<SessionTuning>
    .....
    .....
</SessionTuning>

</SessionTuningData>
<Client>
<nClient_ID>32</nClient_ID>
<strAddress></strAddress>
<strCity></strCity>
<strCountry></strCountry>
<strFirstName>Eric</strFirstName>
<strImage>IDF_Eric duBosc.JPG</strImage>
<strLastName>Bosc</strLastName>
<strMI>du</strMI>
<strNote>ikke</strNote>
<strPhoneNum></strPhoneNum>
<strPostalCode></strPostalCode>
<strState></strState>
<strWorkPhone></strWorkPhone>
</Client>
<SE-5 />
</DocumentElement>

With multiple SessionTuning, Now I want to import this XML in my String Array.

My existing code:

public static clsSessionTuningData[] GetSessionTuningFromXMLFile(string FileName)
        {
            try
            {

                StreamReader objReader = new StreamReader(FileName);
                string strData = objReader.ReadToEnd();
                objReader.Close();

                int nStart = 0, nEnd = 0;
                nStart = strData.IndexOf("<SessionTuningData>");
                nEnd = strData.IndexOf("</SessionTuningData>");
                if (nStart > 0 && nEnd > 0)
                {

                    nStart = nStart + "<SessionTuningData>".Length;
                    nEnd = nEnd + "</SessionTuningData>".Length;
                    strData = strData.Substring(nStart + 1, nEnd - nStart - 1);
                    string[] strSessionTuning = strData.Split('\r', '\n');
                    clsSessionTuningData[] objSessionTuning = new clsSessionTuningData[1];
                    clsDataType.XMLType objXML = new clsDataType.XMLType();

                    int j = 0;
                    for (int i = 0; i < strSessionTuning.GetLength(0); i++)
                    {
                        objXML = clsCommonFunc.GetXML(strSessionTuning[i]);

                        if (objXML != null)
                        {
                            switch (objXML.Name)
                            {
                                case "Revision2":
                                    objSessionTuning[j].bRevision2 = clsCommonFunc.IsYes(objXML.Value);
                                    break;
                                case "Revision3":
                                    objSessionTuning[j].bRevision3 = clsCommonFunc.IsYes(objXML.Value);
                                    break;
                                case "Revision4":
                                    objSessionTuning[j].bRevision4 = clsCommonFunc.IsYes(objXML.Value);
                                    break;
                                case "Revision5":
                                    objSessionTuning[j].bRevision5 = clsCommonFunc.IsYes(objXML.Value);
                                    break;
                                case "Revision6":
                                    objSessionTuning[j].bRevision6 = clsCommonFunc.IsYes(objXML.Value);
                                    break;
                                case "TuningIsNegative":
                                    objSessionTuning[j].bTuningIsNegative = clsCommonFunc.IsYes(objXML.Value);
                                    break;
                                case "Session_ID":
                                    objSessionTuning[j].nSession_ID = int.Parse(objXML.Value);
                                    break;
                                case "SessionTuning_ID":
                                    objSessionTuning[j] = new clsSessionTuningData();
                                    objSessionTuning[j].nSessionTuning_ID = int.Parse(objXML.Value);
                                    break;
                                case "TuningAddInfo":
                                    objSessionTuning[j].nTuningAddInfo = int.Parse(objXML.Value);
                                    break;
                                case "Amp":
                                    objSessionTuning[j].strAmp = objXML.Value;
                                    break;
                                case "Amp2":
                                    objSessionTuning[j].strAmp2 = objXML.Value;
                                    break;
                                case "Amp3":
                                    objSessionTuning[j].strAmp3 = objXML.Value;
                                    break;
                                case "Amp4":
                                    objSessionTuning[j].strAmp4 = objXML.Value;
                                    break;
                                case "Amp5":
                                    objSessionTuning[j].strAmp5 = objXML.Value;
                                    break;
                                case "Amp6":
                                    objSessionTuning[j].strAmp6 = objXML.Value;
                                    break;
                                case "TunFreq":
                                    objSessionTuning[j].strTunFreq = objXML.Value;
                                    break;
                                case "TunFreq2":
                                    objSessionTuning[j].strTunFreq2 = objXML.Value;
                                    break;
                                case "TunFreq3":
                                    objSessionTuning[j].strTunFreq3 = objXML.Value;
                                    break;
                                case "TunFreq4":
                                    objSessionTuning[j].strTunFreq4 = objXML.Value;
                                    break;
                                case "TunFreq5":
                                    objSessionTuning[j].strTunFreq5 = objXML.Value;
                                    break;
                                case "TunFreq6":
                                    objSessionTuning[j].strTunFreq6 = objXML.Value;
                                    break;
                                case "Tuning":
                                    objSessionTuning[j].strTuning = objXML.Value;
                                    break;

                                case "TuningDescr":
                                    objSessionTuning[j].strTuningDescr = objXML.Value;
                                    break;
                                case "AlreadyBalanced":
                                    objSessionTuning[j].bAlreadyBalanced = clsCommonFunc.IsYes(objXML.Value);
                                    break;
                                case "ImagePath":
                                    objSessionTuning[j].strImagePath = objXML.Value;
                                    break;
                                case "Amp7":
                                    objSessionTuning[j].strAmp7 = objXML.Value; // Krunal on 2-2-2012
                                    break;
                                case "TunFreq7":
                                    objSessionTuning[j].strTunFreq7 = objXML.Value;
                                    break;
                                case "Revision7":
                                    objSessionTuning[j].bRevision7 = clsCommonFunc.IsYes(objXML.Value);
                                    break;
                                case "Description":
                                    objSessionTuning[j].Description = objXML.Value;
                                    break;
                                case "TunRevDate":
                                    objSessionTuning[j].strRevDate = Convert.ToDateTime(objXML.Value);
                                    break;
                                case "TunRevDate2":
                                    objSessionTuning[j].strRevDate2 = Convert.ToDateTime(objXML.Value);
                                    break;
                                case "TunRevDate3":
                                    objSessionTuning[j].strRevDate3 = Convert.ToDateTime(objXML.Value);
                                    break;
                                case "TunRevDate4":
                                    objSessionTuning[j].strRevDate4 = Convert.ToDateTime(objXML.Value);
                                    break;
                                case "TunRevDate5":
                                    objSessionTuning[j].strRevDate5 = Convert.ToDateTime(objXML.Value);
                                    break;
                                case "TunRevDate6":
                                    objSessionTuning[j].strRevDate6 = Convert.ToDateTime(objXML.Value);
                                    break;
                                case "TunRevDate7":
                                    objSessionTuning[j].strRevDate7 = Convert.ToDateTime(objXML.Value);
                                    break;
                                case "Tuning_ID":
                                    objSessionTuning[j].nTuning_ID = int.Parse(objXML.Value);
                                    j++;//this is last field so increment by one,
                                    Array.Resize(ref objSessionTuning, j + 1);
                                    break;
                            }
                        }
                    }
                    return objSessionTuning;
                }
                return null;
            }
            catch (Exception ex)
            {
                clsErrorTrace.CreateLog("SessionTuning", ex);
                return null;
            }
        }

But this works if I know the Last attribute that is Tuning_ID.

Is there an easy way to go with this..?

Vishal Suthar
  • 17,013
  • 3
  • 59
  • 105
  • 2
    Oh my god! Did you hear anything about `Serialization`? – Mohammad Dehghan Feb 27 '13 at 13:27
  • Yes, I heard about that, but have no idea regarding that. – Vishal Suthar Feb 27 '13 at 13:28
  • @VishalSuthar I suggest you start by learning about xml serialization. It simplifies things like that a lot: http://tech.pro/tutorial/798/csharp-tutorial-xml-serialization – Botz3000 Feb 27 '13 at 13:33
  • an example can be found here: [http://stackoverflow.com/questions/364253/how-to-deserialize-xml-document][1] [1]: http://stackoverflow.com/questions/364253/how-to-deserialize-xml-document – string.Empty Feb 27 '13 at 13:44

2 Answers2

3

Of course there are much simpler ways to do this. One of them is called Serialization, in which you can convert an entire class to some kind of stream, namely XML and Bytes. You use the XmlSerializer class for this. Here is a simple example:

Suppose you have a class that you want to store in and XML file:

[Serializable] // you should mark the class as serializable
public class MyData
{
    public int Value { get; set; }
    public string Name { get; set; }
    public string[] SubItems { get; set; }
}

This code converts it to an XML file:

MyData data = new MyData();
data.Name = "TestName";
data.Value = 100;
data.SubItems = new string[] {"Item1", "Item2", "Item3"};
XmlSerializer ser = new XmlSerializer(typeof(MyData));
using (FileStream file = new FileStream(fileName, FileMode.Create, FileAccess.Write))
{
    ser.Serialize(file, data);
}

Here is the resulting file:

<?xml version="1.0"?>
<MyData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Value>100</Value>
  <Name>TestName</Name>
  <SubItems>
    <string>Item1</string>
    <string>Item2</string>
    <string>Item3</string>
  </SubItems>
</MyData>

To read the file, you use the Deserialize method:

using (FileStream file = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
    ser.Deserialize(file, data);
}

The other option is to use one of the specialized classes in .NET framework to read the XML file:

XDocument doc = XDocument.Load(fileName);
List<clsSessionTuningData> objSessionTuning = new List<clsSessionTuningData>()
foreach (var session in doc.Descendants("SessionTuningData"))
{
    XElement elem;
    clsSessionTuningData data = new clsSessionTuningData();
    elem = session.Element("Revision2");
    if (elem != null)
        data.bRevision2 = elem.Value;

    // and so on...
}
Mohammad Dehghan
  • 17,853
  • 3
  • 55
  • 72
0

You could:

1) load your XML into an XMLDocument, then navigate the document through its properties (mainly ChildNodes);

2) load your XML into an XMLDocument, then query the document using XPath, creating a navigator via CreateNavigator.

3) Parse your document with an XmlReader.

4) Create a set of classes closely related to your Xml schema, and use a XmlDeserializer to map a file to a set of objects (this is great, but tricky to set up, as the XmlDeserializer can be a bit stubborn to configure).

If I needed ALL the data, I'd go for option (4), possibly redesigning my XML/model classes to make the conversion easier.

If i needed some of the values, I'd probably go for (2), as it requires very little code. See some examples of (2) here.

Mau
  • 14,234
  • 2
  • 31
  • 52