从对象列表生成Xelement

时间:2014-01-21 13:47:23

标签: c# .net xmldocument 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的int

输出

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

任何解决方案

2 个答案:

答案 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))
                             ));

这将为您提供预期的输出。

答案 1 :(得分: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))
                         ));