简体   繁体   中英

C# Create XML File from with more than one dataset (one being for details)

Im not the most experienced developer so excuse me if I have not used the correct terms here.

I want to create an XML file in visual studio using C# from data from SQL server.

The data will come from two dataset. The first will be the main 'header' details and then the second will be the 'line detail' for each of these headers.

I want the code to first loop through the header dataset, add all columns to the xml and then before moving onto the next row, it will loop through the second dataset and find the rows the match up to the current row of the first dataset (by ID) and add all those rows to the XML.

There can only be one unique header but this can have more than one line detail. The XML should look something like below, where header is the from the first dataset and line is the second (Just example data):

    <?xml version="1.0"?>
    <Header>
        <ID>1</ID>
        <Name>James</Name>
        <Address>12 London Road</Address>
        <TelNumber>07543430921</TelNumber>
        <Line>
            <LineItem>
                <OrderNo>0001</OrderNo>
                <Price>100.00</Price>
                <Tax>20.00</Tax>
                <Delivery>5.00</Delivery>
            </LineItem>
            <LineItem>
                <OrderNo>0002</OrderNo>
                <Price>200.00</Price>
                <Tax>20.00</Tax>
                <Delivery>6.00</Delivery>
            </LineItem>
         </Line>
    </Header>
    <Header>
        <ID>2</ID>
        <Name>Danny</Name>
        <Address>56 High Street</Address>
        <TelNumber>07698903111</TelNumber>
        <Line>
            <LineItem>
                <OrderNo>0005</OrderNo>
                <Price>300.00</Price>
                <Tax>20.00</Tax>
                <Delivery>9.99</Delivery>
            </LineItem>
        </Line>
    </Header>

I have no idea how to code this so any help with me greatly appreciated.

Thanks

I will suggest to create DTOs for Header and Lines, have List<Line> available in the Header DTO, you can retrieve data as you want and prepare List<Header> from this data and use sterilizer to convert it into XML.

You can have first your XSD and you can generate DTOs from XSD using XSD.exe or XSD2Code , use this generated DTO that will give you fine control on how XML should be generated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM