Domanda

I create an XML document using the below code

For Each cust As Customer In Customers
XDoc = <?xml version="1.0" encoding="UTF-16" standalone="yes"?>
<Customers>
<Customer>
<Name>Mike</Name>
<Age>0</Age>
</Customer>
</Customers>
Next

XDoc.Save("C:\myXmlfile.xml")

However it only seems to add one record, but i dont know how to readd the nodes for each record? So if theres 2 records then i would expect

<?xml version="1.0" encoding="UTF-16" standalone="yes"?>
<Customer>
<Name>Mike</Name>
<Age>0</Age>
</Customer>
<Customer>
<Name>Mike</Name>
<Age>0</Age>
</Customer>

but it should only generate one xml file.

Could anyone guide me in what i need to do please? Even after searching around im not 100% sure as theres too many methods and ive probably got confused.

Thanks

È stato utile?

Soluzione 3

In addition to @RichardSchneider's answer, this is sample snippet in VB.

First, construct XDocument with single <Customers> element as root. Then in each iteration of For Each loop, add single <Customer> element to the root element of the XDocument :

XDoc As XDocument = <?xml version="1.0" encoding="UTF-16" standalone="yes"?><Customers></Customers>
For Each cust As Customer In customers
    XDoc.Root.Add(
        <Customer>
            <Name>Mike</Name>
            <Age>0</Age>
        </Customer>
    )
Next
XDoc.Save("C:\myXmlfile.xml")

Altri suggerimenti

Inside the loop you set XDoc to the the customer. This means that when you save XDOC ONLY the last customer will be saved.

Even if you fix the above, you still have the issue that you are trying to add multiple root elements (each customer) to the XML document. This is not allowed, only one root element is allowed. So to produce a valid XML document, you want something like:

 <Customers>
   <Customer>
     <Name>Mike</Name>
     <Age>0</Age>
   </Customer>
   <Customer>
     <Name>Mike</Name>
     <Age>0</Age>
   </Customer>
 </Customers>

I'm sorry but I can recommend how to change your code, because I don't know the VB.Net extensions for XML. Hopefully, someone else will shed some light.

BTW, interesting handle.

You can generate XDocument and XElement separately.
Further, you can set data from variable using <%= %>.

Therefore, you should generate and combine like below.

' Generate customers
Dim customers As XEelement = <Customers></Customers>
For Each cust As Customer In Customers
    customers.Add( 
        <Customer>
            <Name><%= cust.Name %></Name>
            <Age><%= cust.Age %></Age>
        </Customer>
    )
Next

' Combine customers
Dim XDoc As XDocument = 
    <?xml version="1.0" encoding="UTF-16" standalone="yes"?><%= customers %>
XDoc.Save("C:\myXmlfile.xml")
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top