CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 11 of 11
  1. #1
    Join Date
    May 2010
    Posts
    6

    Lightbulb using xml to parse a data file in C#

    I have two files

    File 1 contents:
    0908070605040302

    File 2 contents:
    <SOME_NUMBER>8</SOME_NUMBER>
    <SOME_TYPE1>2</SOME_TYPE1>
    <SOME_TYPE2>2</SOME_TYPE2>
    <SOME_REVISION>2</SOME_REVISION>
    <SOME_CODE>2</SOME_CODE>

    i wanna write a windows form app in C# express edition to display the following on a windows form

    Labels textboxes
    ----------------- --------------
    Some Number 09080706
    Some type1 05
    Some type2 04
    Some revision 03
    Some Code 02

  2. #2
    Join Date
    May 2010
    Posts
    2

    Re: using xml to parse a data file in C#

    [CHARP]
    XDocument doc = XDocument.Load("file2path\file2name.xml");
    int S_N=(int)doc.Element("SOME_NUMBER").Value;
    int S_T1=(int)doc.Element("SOME_TYPE1").Value;
    int S_T2=(int)doc.Element("SOME_TYPE2").Value;
    int S_R=(int)doc.Element("SOME_REVISION").Value;
    int S_C=(int)doc.Element("SOME_CODE").Value;

    StreamReader stream =new StreamReader("file1path\file1name.xml")
    string str=stream.ReadToEnd();
    txtBox1.Text=str.Substring(0,S_N);
    txtBox2.Text=str.Substring(S_N,S_T1);
    txtBox3.Text=str.Substring(S_T1,S_T2);
    txtBox4.Text=str.Substring(S_T2,S_R);
    txtBox5.Text=str.Substring(S_R,S_C);
    [/CHARP]

  3. #3
    Join Date
    May 2010
    Posts
    6

    Thumbs up Re: using xml to parse a data file in C#

    awesome!

    Thanks a bunch!

    EvgenOrel you rock!


    I have one question though... my first file is not an xml file... its a txt file... will it make any difference?

    I see you are trying to read the entire file.. what if the data file is about 2MB... can the C# application handle that much data without crashing?

    Appreciate your response.

    -Sam

  4. #4
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: using xml to parse a data file in C#

    Neither file is valid xml.

  5. #5
    Join Date
    May 2010
    Posts
    6

    Re: using xml to parse a data file in C#

    C# gives compilation error for

    int S_N = (int) doc.Element("SOME_NUMBER").Value.;

    cannot convert string to int. any suggestions?

  6. #6
    Join Date
    May 2007
    Posts
    1,546

    Re: using xml to parse a data file in C#

    I see you are trying to read the entire file.. what if the data file is about 2MB... can the C# application handle that much data without crashing?
    2mb can hardly be considered a lot of data Memory consumption will be less if you don't read the entire file into memory in one go but instead parse it line by line using streamreader.ReadLine ().

    Code:
    int S_N = int.Parse (doc.Element("SOME_NUMBER").Value);
    You can't cast a string to an int, but you can parse an integer value from a string.
    www.monotorrent.com For all your .NET bittorrent needs

    NOTE: My code snippets are just snippets. They demonstrate an idea which can be adapted by you to solve your problem. They are not 100% complete and fully functional solutions equipped with error handling.

  7. #7
    Join Date
    May 2010
    Posts
    6

    Re: using xml to parse a data file in C#

    Thanks.

    I now get different error msgs.

    1. Multiple root exists, so i changed the xml file as follows

    <DBASE>
    <SOME_NUMBER>8</SOME_NUMBER>
    <SOME_TYPE1>2</SOME_TYPE1>
    <SOME_TYPE2>2</SOME_TYPE2>
    <SOME_REVISION>2</SOME_REVISION>
    <SOME_CODE>2</SOME_CODE>
    </DBASE>

    and my code as

    private void button1_Click(object sender, EventArgs e)
    {
    XDocument doc = XDocument.Load("ds.xml");
    StreamReader stream = new StreamReader("database.dat");
    string str=stream.ReadToEnd();
    int S_N = int.Parse(doc.Element("SOME_NUMBER").Value);
    int S_T1 = int.Parse(doc.Element("SOME_TYPE1").Value);
    int S_T2 = int.Parse(doc.Element("SOME_TYPE2").Value);
    int S_R = int.Parse(doc.Element("SOME_REVISION").Value);
    int S_C = int.Parse(doc.Element("SOME_CODE").Value);

    textBox9.Text = str.Substring(0, S_N);
    textBox10.Text = str.Substring(S_N, S_T1);
    textBox11.Text = str.Substring(S_T1, S_T2);
    textBox12.Text = str.Substring(S_T2, S_R);
    textBox13.Text = str.Substring(S_R, S_C);
    }

    now i get error msg on the line defining S_N

    int S_N = int.Parse(doc.Element("SOME_NUMBER").Value);

    attached screen shot
    Attached Images Attached Images

  8. #8
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: using xml to parse a data file in C#

    Another approach is to leverage Xml Serialization which reads an xml file and creates a C# class instance.

    The first thing to do is create a class that represents the xml schema. You can use tools to do this like XSD.exe, but on something this simple it's easy enough to add the required serialization attributes.

    First I've modified the xml file to follow typical naming conventions and take a few enum types:

    Code:
    <dBase>
    <number>8</number>
    <type1>Red</type1>
    <type2>Medium</type2>
    <revision>2.0.4</revision>
    <code>2</code>
    </dBase>


    Next, create the DBase serialization class which has a static method that reads the xml file and creates an instance of the class. Notice the Serialization attributes which decorate the class and its properties. These attributes let the serializer know what properties to serialize and how.

    Code:
     
    [Serializable( )]
    publicenumTypes1 { Red, Green, Blue };
     
    [Serializable( )]
    publicenumTypes2 { Low, Medium, High };
     
    ///<remarks/>
    [Serializable( )]
    [XmlType( AnonymousType = true )]
    [XmlRoot( ElementName = "dBase", Namespace = "", IsNullable = false )]
    publicclassDBase
    {
     
      ///<summary/>
      publicstaticDBase Load( string dbaseFile )
      {
        XmlSerializer serializer = newXmlSerializer( typeof( DBase ) );
     
         using ( XmlReader reader = XmlReader.Create( dbaseFile ) )
        {
          return ( DBase ) serializer.Deserialize( reader );
        }
      }
     
      ///<remarks/>
      [XmlElement( "number" )]
      publicint Number { get { return _number; } set { _number = value; } }
    
      ///// <remarks/>
      [XmlElement( "type1" )]
      publicTypes1 Type1 { get { return _type1; } set { _type1 = value; } }
     
      ///<remarks/>
      [XmlElement( "type2" )]
      publicTypes2 Type2 { get { return _type2; } set { _type2 = value; } }
     
      ///<remarks/>
      [XmlElement( "revision" )]
      publicstring Revision { get { return _revision; } set { _revision = value; } }
     
      ///<remarks/>
      [XmlElement( "code" )]
      publicint Code { get { return _code; } set { _code = value; } }
     
      privateint _number;
      privateTypes1 _type1;
      privateTypes2 _type2;
      privatestring _revision;
      privateint _code;
    }
    


    Finally, reading the xml is pretty straightforward:


    Code:
     
    privatevoid buttonLoad_Click( object sender, EventArgs e )
    {
      DBase db = DBase.Load( "dbase.xml" );
     
      textBoxNumber.Text = Convert.ToString( db.Number );
      textBoxType1.Text = Convert.ToString( db.Type1 );
      textBoxType2.Text = Convert.ToString( db.Type2 );
      textBoxRevision.Text = db.Revision;
      textBoxCode.Text = Convert.ToString( db.Code );
    }
    
    Attached Files Attached Files

  9. #9
    Join Date
    May 2010
    Posts
    6

    Re: using xml to parse a data file in C#

    Arjay,

    you did a pretty excellent job by giving that example. Now I understand how to read xml files...

    But this is not how my xml file is to be used. The xml file i have, has the tags (which are nothing but the variables) and values within the tags(which are nothing but the number of characters to read from the data file).

    so, once again - if my tag says

    <SOME_NUMBER>8</SOME_NUMBER>

    that means i need to read 8 characters from the data file which contains
    0908070605040302
    I should fill my textbox with 8 characters 09080706 for the field named SOME_NUMBER and so on...

    thanks again.

  10. #10
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: using xml to parse a data file in C#

    Quote Originally Posted by mrunmoy View Post
    Arjay,

    you did a pretty excellent job by giving that example. Now I understand how to read xml files...

    But this is not how my xml file is to be used. The xml file i have, has the tags (which are nothing but the variables) and values within the tags(which are nothing but the number of characters to read from the data file).
    So I gave you an example of how to read a string, integer and enum values from xml. Modify my example as appropriate for your needs. My goal isn't to do the work for you, but to give you a technique that you can use to solve your problem.

  11. #11
    Join Date
    May 2010
    Posts
    6

    Thumbs up Re: using xml to parse a data file in C#

    I thought I would have to declare enums for reading numbers too. I guess I missed that part of the code and realized it later but it was too late and I had already posted again... but yes, you're right... now I can use this snippet to serve my purpose..

    Thanks again.

    Cheers!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured