2014-01-21 66 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只返回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查詢分解成更小的塊。 IT將更易於編寫,閱讀和維護。與無法讀取的編碼相比,擁有一些額外的代碼通常具有非常小的計算機成本。 –

+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)) 
         ));