2014-01-21 3 views
-1

Мой кодСоздание XElement из списка объекта

IList<Person> people=new List<Person>(); 
      people.Add(new Person{Id=1,Name="Nitin"}); 

     IList<decimal> my=new List<decimal>(){1,2,3}; 
     IList<int> your=new List<int>(){1,2,3}; 

     XElement xml = new XElement("people", 
          from p in people 
          select new XElement("person", new XAttribute("Id", "Hello"), 
             new XElement("id", p.Id), 
             new XElement("Mrp", my.Contains(1) ? string.Join(",",my):"Nitin"), 
             new XElement("Barcode", Form1.GetStrings(1).Select(i => new XElement("Barcode", i))) 
             )); 
     MessageBox.Show(xml.ToString()); 

GetStrings только возвращает Int от 1 до 4

Выход

<people> 
    <person Id="Hello"> 
    <id>1</id> 
    <Mrp>1,2,3</Mrp> 
    <Barcode> 
     <Barcode>1</Barcode> 
     <Barcode>2</Barcode> 
     <Barcode>3</Barcode> 
     <Barcode>4</Barcode> 
    </Barcode> 
    </person> 

</people> 

Но я хочу выход как

<people> 
      <person Id="Hello"> 
      <id>1</id> 
      <Mrp>1,2,3</Mrp> 
      <Barcode>1</Barcode> 
       <Barcode>2</Barcode> 
       <Barcode>3</Barcode> 
       <Barcode>4</Barcode> 
      </person> 
</people> 

Любые решения

+6

ваш идеальный выход не является допустимым XML. Он имеет закрывающий тег '' тега соответствующего тега открытия. Кроме того, отсутствует тег закрытия ''. В противном случае, я не вижу никакой разницы между вашим текущим выходом и идеальным выходом. – DaveDev

+0

Мне не нравится иметь такую ​​* одну строку, которая делает все *. Вы должны разложить свой запрос Linq на более мелкие куски. ИТ было бы легче писать, читать и поддерживать. Наличие некоторого дополнительного кода часто имеет очень небольшую стоимость компьютера по сравнению с нечитаемым кодеком. –

+0

Проблема только при вклеивании –

ответ

3

Тогда вместо этого:

new XElement("Barcode", Form1.GetStrings(1).Select(i => new XElement("Barcode", i))) 

Используйте свой запрос непосредственно, как это, не создают дополнительный Barcode элемент:

Form1.GetStrings(1).Select(i => new XElement("Barcode", i)) 

Тогда ваш код должен выглядеть следующим образом:

XElement xml = new XElement("people", 
         from p in people 
         select new XElement("person", new XAttribute("Id", "Hello"), 
            new XElement("id", p.Id), 
            new XElement("Mrp", my.Contains(1) ? string.Join(",",my):"Nitin"), 
            Form1.GetStrings(1).Select(i => new XElement("Barcode", i)) 
          )); 

Это даст вам ожидаемый результат.

0

Попробуйте это:

XElement xml = new XElement("people", 
        from p in people 
        select new XElement("person", new XAttribute("Id", "Hello"), 
           new XElement("id", p.Id), 
           new XElement("Mrp", my.Contains(1) ? string.Join(",",my):"Nitin"), 
           Form1.GetStrings(1).Select(i => new XElement("Barcode", i)) 
         )); 
Смежные вопросы