2012-03-06 13 views
-7

可能性の重複:
Best practices to parse xml files?XML解析

私はXML文字列があります。

<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> 

を、私はオブジェクト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;} 
    } 

どうFASTこのXML解析し、XML内のすべてのMovieためClass1オブジェクトを作成するには?

+0

このWebサイトはGoogleと呼ばれており、C#でXMLを解析するとLinqからXmlが検索されます... http://msdn.microsoft.com/en-us/library/bb387098.aspx – Lloyd

答えて

2

私はヘルパーメソッドで、XMLにLINQを使用したい:

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"), 
      }; 

Property要素の多くは、実際に存在する場合は、あなたが辞書にそれらを有効にする必要があります

Properties = element.Element("Properties") 
        .Elements("Property") 
        .ToDictionary(x => (string) x.Attribute("Name"), 
            x => (string) x);