2016-10-13 5 views
0

나는 (단일 역 직렬화 여러 XML 태그는

<ConfigData> 
    <Common> 
    <price>1234</price> 
    <color>pink</color>  
    </Common> 
    <SampleProduct> 
    <sample1>new</sample1> 
    <sample2>new</sample2> 
    <sample3>new123</sample3> 
    </SampleProduct> 
</ConfigData> 

가 지금은 SampleProduct 개체에 대한 전체 XML 데이터를 역 직렬화하고 싶었 다음과 같이 내가 XML 파일이 클래스 구조를 가지고 개체). XML 데이터를 다른 개체로 역 직렬화 할 수 있지만 단일 개체로 역 직렬화 할 수는 없습니다. 도와주세요. 당신이 XML을 작성하는 경우

+0

XML 파일을 직접 만드시겠습니까? 아니면 다른 곳에서 제공합니까? – Emad

+0

"ConfigData"라는 새 클래스 이름을 만들고 해당 클래스에 Common 및 SampleProduct를 퇴비에 넣기 만하면됩니다. deserialization보다 ConfigData를 사용하십시오 – Kayani

+0

클래스 구조를 수정하는 편집을 제안 했으므로 찾고 계십니까? –

답변

0

자신이 그냥 이런 식으로 작업을 수행합니다

<ConfigData> 
    <SampleProduct> 
    <price>1234</price> 
    <color>pink</color>  
    <sample1>new</sample1> 
    <sample2>new</sample2> 
    <sample3>new123</sample3> 
    </SampleProduct> 
</ConfigData> 

그렇지 않으면, 당신은 카야 니는 그의 의견에 무엇을 제안 할 다른 소스에서 XML을 얻는 경우 :

public class ConfigData 
{ 
    public Common { get; set; } 
    public SampleProduct { get; set; } 
} 

그러나 이 방식으로 생성 된 SampleProduct는 "가격"및 "색상"속성이없고 생성 된 공통 인스턴스를 사용하여 설정해야 함을 잊지 마십시오.

0

다음은 완전한 솔 ution 제공된 XML을 사용하십시오.

public static void Main(string[] args) 
    { 
     DeserializeXml(@"C:\sample.xml"); 
    } 
    public static void DeserializeXml(string xmlPath) 
    { 
     try 
     { 
      var xmlSerializer = new XmlSerializer(typeof(ConfigData)); 
      using (var xmlFile = new FileStream(xmlPath, FileMode.Open)) 
      { 
       var configDataOSinglebject = (ConfigData)xmlSerializer.Deserialize(xmlFile); 
       xmlFile.Close(); 
      } 
     } 
     catch (Exception e) 
     { 
      throw new ArgumentException("Something went wrong while interpreting the xml file: " + e.Message); 
     } 
    } 

    [XmlRoot("ConfigData")] 
    public class ConfigData 
    { 
     [XmlElement("Common")] 
     public Common Common { get; set; } 

     [XmlElement("SampleProduct")] 
     public SampleProduct XSampleProduct { get; set; } 
    } 

    public class Common 
    { 
     [XmlElement("price")] 
     public string Price { get; set; } 

     [XmlElement("color")] 
     public string Color { get; set; } 
    } 

    public class SampleProduct 
    { 
     [XmlElement("sample1")] 
     public string Sample1 { get; set; } 

     [XmlElement("sample2")] 
     public string Sample2 { get; set; } 

     [XmlElement("sample3")] 
     public string Sample3 { get; set; } 
    } 

이렇게하면 필요한 모든 요소가 포함 된 단일 개체가 제공됩니다.

+0

configDataOSinglebject 변수가 객체를 제공합니다. 나는 거기에 코멘트를 추가하는 것을 잊었다. – Lykanox