2012-06-29 3 views
1

다음과 같은 클래스가 있습니다. 번호는 0에서 n까지 다양 할 수있는 쇼핑 항목을 포함합니다.리스트 용 XMLSerialization

아래와 같이 XML 스키마를 얻는 것처럼 직렬화 된 클래스를 가져올 수 있습니까?

<?xml version="1.0" encoding="utf-8" ?> 
<ShoppingItems> 
<CustomerName>John</CustomerName> 
<Address>Walstreet,Newyork</Address> 
<Item1>Milk</Item1> 
<Price1>1$</Price1> 
<Item2>IceCream</Item2> 
<Price2>1$</Price2> 
<Item3>Bread</Item3> 
<Price3>1$</Price3> 
<Item4>Egg</Item4> 
<Price4>1$</Price4> 


<Item..n>Egg</Item..n> 
<Price..n>1$</Price..n> 
</ShoppingItems> 

이 스키마를 달성하는 가장 좋은 방법은 무엇인지 Serilization을 사용하여 달성 할 수 있는지 알고 싶습니다.

+0

, 나는 유일한 방법은 그것을 할 것입니다 생각하여 자기하지만이 같은 XML 파일이있을 때 당신이 알고, 그것은 (심지어 다른 언어로) 쿼리에 조금 어렵습니다, 나는 우유 1 $ 같은 것을 사용하는 것이 좋습니다 –

답변

4

해당 레이아웃을 지원하는 표준 직렬 변환기가 없습니다. 너 혼자해야 해. 개인적으로, 나는 "당신이 잘못하고있다"고 말할 것입니다; (가능한 경우) 난 강력하게XmlSerializer와 사소한 것 둘 다

<Item name="IceCream" Price="1$"/> 

또는

<Item><Name>IceCream</Name><Price>1$</Price></Item> 

같은 형식을 사용하는 것이 좋습니다 . 당신이 아래의 코드로 볼 수 예를 들어

var items = new ShoppingItems 
{ 
    Address = "Walstreet,Newyork", 
    CustomerName = "John", 
    Items = new List<Item> 
    { 
     new Item { Name = "Milk", Price = "1$"}, 
     new Item { Name = "IceCream", Price = "1$"}, 
     new Item { Name = "Bread", Price = "1$"}, 
     new Item { Name = "Egg", Price = "1$"} 
    } 
}; 

var xml = new XElement("ShoppingItems", 
    new XElement("CustomerName", items.CustomerName), 
    new XElement("Address", items.Address), 
    items.Items.Select((item,i)=> 
     new[] { 
      new XElement("Item" + (i + 1), item.Name), 
      new XElement("Price" + (i + 1), item.Price)})) 
    .ToString(); 
+0

XML 스키마에서는 그다지 말하지 않습니다. 따라서 XElement 또는 XmlWriter를 사용하여 스키마를 필요로합니다. 고마워 .. – Nayan

0

당신이 내 기사에 봐 주실 래요, [^]

:

LINQ - 투 - XML은 아마 당신의 최선의 선택, 같은 것입니다 . 메서드를 serialize하려면이 기사를 참조하십시오. 난 당신이 그물 sezialization 공예와 함께 할 수 있다는 것을 확실하지 않다

var test = new ShoppingItems() 
          { 
           CustomerName = "test", 
           Address = "testAddress", 
            Items = new List<Item>() 
               { 
                new Item(){ Name = "item1", Price = "12"}, 
                new Item(){Name = "item2",Price = "14"} 
               }, 
          }; 

      var xmlData = Serialize(test); 

그리고 그것은 문자열이 아래 반환합니다

<?xml version="1.0" encoding="utf-16"?> 
<ShoppingItems xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
    <CustomerName>test</CustomerName> 
    <Address>testAddress</Address> 
    <Items> 
     <Item> 
      <Name>item1</Name> 
      <Price>12</Price> 
     </Item> 
     <Item> 
      <Name>item2</Name> 
      <Price>14</Price> 
     </Item> 
    </Items> 
</ShoppingItems> 
+0

a : 그것은 OP가 요청한 구조가 아니며, b : 그 기사는 XmlSerializer의 가장 사소한 사용법에 대한 기본적인 내용 일뿐입니다. 솔직히 [MSDN 설명서] (http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx)가 훨씬 더 나은 리소스가 될 것입니다. –