-7

Possible Duplicate:
Best practices to parse xml files?

I have a xml string:

<XML>
  <Result>Ok</Result>
  <Error></Error>
  <Remark></Remark>
  <Data>
    <Movies>
      <Movie ID='2'> // in this xml only one Movie, but may be more
        <Name>
          <![CDATA[Name1]]>
        </Name>
        <Duration Duration='170'>2h 50m</Duration>
        <OtherName>
          <![CDATA[Other name]]>
        </OtherName>
        <SubName>
          <![CDATA[sub]]>
        </SubName>
        <UpName>
          <![CDATA[up]]>
        </UpName>
        <Remark>
          <![CDATA[]]>
        </Remark>
        <Picture>
          <![CDATA[507.jpg]]>
        </Picture>
        <Properties>
          <Property Name='Property1'>
            <![CDATA[property1Text]]>
          </Property>
          <Property Name='Property2'>
            <![CDATA[property2Text]]>
          </Property>
        </Properties>
        <Rental from_date='' to_date=''>
          <SessionCount></SessionCount>
          <PU_NUMBER></PU_NUMBER>
        </Rental>
      </Movie>
    </Movies>
  </Data>
</XML>

and I have object Class1:

    public class Class1
    {
       public string Subject {get; set;}
       public string OtherName {get; set;}
       public string Property1 {get; set;}
       public string Property2 {get; set;}
       public int Duration {get; set;}
       public int Id {get; set;}
    }

How to parse FAST this xml and create Class1 object for every Movie in xml?

Community
  • 1
  • 1
user1230307
  • 92
  • 1
  • 2
  • 7

1 Answers1

2

I'd use LINQ to XML, with a helper method:

var movies = from element in XDocument.Parse(xml).Descendants("Movie")
             select new Class1
             {
                 Id = (int) element.Attribute("ID"),
                 Subject = (string) element.Element("Name"),
                 OtherName = (string) element.Element("OtherName"),
                 Duration = (int) element.Element("Duration")
                                         .Attribute("Duration"),
                 Property1 = (string) element.Element("Properties")
                     .Elements("Property")
                     .Where(x => (string) x.Attribute("Name") == "Property1")
                     .Single(),
                 Property2 = (string) element.Element("Properties")
                     .Elements("Property")
                     .Where(x => (string) x.Attribute("Name") == "Property2")
                     .Single(),
                 Subject = (string) element.Element("Name"),
             };

If there are really a lot of Property elements, you might want to turn them into a dictionary:

Properties = element.Element("Properties")
                    .Elements("Property")
                    .ToDictionary(x => (string) x.Attribute("Name"),
                                  x => (string) x);
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194