Home > Back-end >  How to create and fill an xml file in VB.NET?
How to create and fill an xml file in VB.NET?

Time:06-24

I'm currently in an internship, and I have to check whether or not the necessary XML file for my project is created or not, and, if it doesn't exists, I have to create and fill it with the nodes, but it doesn't work. I can check if the file exists, and if not, I can create it, but that's all. I tried to add the declaration, but that doesn't work either. It just creates the file, without anything inside. Here is the code I wrote to do that :

If Not (File.Exists(filePathTest)) Then
                Using fsCreate As FileStream = File.Create(filePathTest)
                    Dim xmldocCreate As New XmlDataDocument()
                    Dim xmldecl As XmlDeclaration
                    xmldecl = xmldocCreate.CreateXmlDeclaration("1.0", Nothing, Nothing)
                    xmldocCreate.AppendChild(xmldecl)
                End Using
            Else

and what the xml file should look like :

<?xml version="1.0" encoding="utf-8"?>
<Ampoules>
  <ampoule>
    <nom>product name</nom>
    <type>product type</type>
    <sousType>product sub-type</sousType>
    <code>product reference</code>
    <xRay>BW524/99/Ro</xRay>
    <quantity>product quantity</quantity>
  </ampoule>
  <Date>
    <date>23/06/2022</date>
  </Date>
</Ampoules>

Having 57 other <ampoule></ampoule> nodes like that, I can't put them all, so it would be nice if someone has a solution for this problem as well, though I might have an idea of how to do this. I also have to create the <Date></Date> node with a <date></date> inner node and the current day as the inner text, and I don't know either how to do this.

I thank you in advance for your answers.

CodePudding user response:

You'll need to read this XML Literals and this XElement to make sense of this. It creates what I think you want, 57 ampoule nodes. XElement and embedded queries is a powerful feature.

    Dim path As String
    path = "path to xml file"

    Dim xe As XElement
    xe = <Ampoules>
             <%= From z In Enumerable.Range(1, 57)
                 Select <ampoule id=<%= z %>>
                            <nom></nom>
                            <type></type>
                            <sousType></sousType>
                            <code></code>
                            <xRay></xRay>
                            <quantity></quantity>
                        </ampoule>
             %>
             <Date>
                 <date><%= DateTime.Now.ToString("dd/MM/yyyy") %></date>
             </Date>
         </Ampoules>

    xe.Save(path)

To load an XML file

    Dim xe As XElement
    xe = XElement.Load(path)
  • Related