Jawab write XML with XElement

  • 06 Maret 2012 13:23
     
      Memiliki Kode

    Hello guys,

    I want to create XML like this in a loop because I don't know how much data is in my list. I could not find an example, all samples are for pre-defined number of data. 

    So, XML should look like this:

    <AM>
    	<HM>
    		<FullName>aaa</FullName>
    		<ShortName>aa</ShortName>
    		<Code>1</Code>
    	</HM>
    	<HM>
    		<FullName>aaa</FullName>
    		<ShortName>aa</ShortName>
    		<Code>2</Code>
    	</HM>	
    </AM>

    There is only one AM buth a lot of HM's. I store them in a list. 

    I have tried with Exlement.Add but I get an non-closed element like <HM\> and not </HM>.

    Please help.


Semua Balasan

  • 06 Maret 2012 13:30
     
     Jawab

    With C#:

    XDocument doc = new XDocument(

      new XElement("AM",

        from item in yourList

        select new XElement("HM",

          new XElement("FullName", item.FullName),

          new XElement("ShortName", item.ShortName),

          new XElement("Code", item.Code)

       )

     ));

    That's all that is to it. If you still have problems then please post the class or type definition of your list.


    MVP Data Platform Development My blog

    • Ditandai sebagai Jawaban oleh crtlSpace 06 Maret 2012 13:52
    •  
  • 06 Maret 2012 13:37
     
      Memiliki Kode

    OK, i have next problem. 

    Error 3 Could not find an implementation of the query pattern for source type 'AAA.HM.hma'.  'Select' not found.

    List implementation: 

    public List<hma> mat = new List<hma>();
    
    public struct hma
    {
       public String fullName;
       public String shortName;
       public int code;
       public double value;
       public double maxLimit;
       public double MinLimit;
       public Relation relation;
    }
    

  • 06 Maret 2012 13:45
     
     

    If you get an error and you want us to be able to fix it then please show us the code causing the error i.e. state the exact line you get the error for and also show the context like declaration and initialization of all variables involved.

    Obviously without knowing your list type I could only make up an example but other than adapting the property names as in

    XDocument doc = new XDocument(

      new XElement("AM",

        from item in mat

        select new XElement("HM",

          new XElement("FullName", item.fullName),

          new XElement("ShortName", item.fhortName),

          new XElement("Code", item.fode)

       )

     ));

    I don't see any needed changes. Of course the List<hma> mat needs to be populated with some items to get the XML populated too.


    MVP Data Platform Development My blog

  • 06 Maret 2012 13:52
     
     

    I'm sorry I have used declaration of type not instance. My bad. 

    Thank you very much for your help. LINQ is amazing, this is very easy and intuitive.