Help with creating multiple xml files

Hi,

How do you modify the code below to loop through multiple table names in a string variable s = Name,Item,Location,Tasks to create multiple xml files?


Dim xdoc = XElement.Load("C:\Working Directory\AllTables.xml")
' Get all the tableX nodes and there children
Dim tables = From t in xdoc.Descendants() _
             Where t.Name.ToString().StartsWith("Table")
             Select t

' Set up the new XML document and save to the file system            
For Each table In tables
    ' Get the Table number so that we can create the file name with that number
    Dim fileNumber As String = table.Name.ToString().SubString(5)
    ' Create a new Root node and add the TableX as its child
    Dim newRoot = New XElement("Root", table)
    ' Save the new XML document to the file system
    newRoot.Save("C:\Working Directory\File" + fileNumber + ".xml")
Next

Thanks,

Victor
vcharlesAsked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
Fernando SotoConnect With a Mentor RetiredCommented:
Hi Victor;

This code snippet will create a XML file from each child element of the root node using that node's name.

' The directory name from which you will get the main XML file and where to save the smaler XML files.
Dim dirName As String = "C:\Working Directory\"
' Load the original XML file into memory
Dim xdoc As XDocument = XDocument.Load(dirName & "ParseToFiles.xml")

' The results of this query are the nodes to be saved into a there own file 
Dim xFiles As List(Of XElement) = (From f In xdoc.Root.Elements()
                                   Select f).ToList()

' Enumerate list of nodes and save them to the filesystem
For Each node As XElement In xFiles
    Dim fileName = node.Name.ToString() & ".xml"
    node.Save(dirName & fileName)
Next

Open in new window

0
 
Fernando SotoRetiredCommented:
So how do you want the resulting XML files to look like? Maybe something like the following?

<Root>
    <Name>
        <Item><l/Item>
        <Location></Location>
        <Tasks></Tasks>
    </Name>
</Root>

Open in new window

0
 
vcharlesAuthor Commented:
Yes, I would like the following format, where Name will change to the different tables.

<Root>
    <Name>
        <Item><l/Item>
        <Location></Location>
        <Tasks></Tasks>
    </Name>
</Root>

Thanks,

Victor
0
Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

 
Fernando SotoRetiredCommented:
Hi Victor;

This should give you what you want.

' Test input data
Dim s = "Name1,Item,Location,Tasks,Name2,Item,Location,Tasks,Name3,Item,Location,Tasks"
' Split the input data into an array of strings
Dim sSplit = s.Split(",")
' Assign every 4 elements to a list of string Representing one set of data
Dim names As New List(Of List(Of String))

' Turn the array of strings to a List(Of List(Of String))
For i As Integer = 0 To sSplit.Length - 1 Step 4
    Dim nameItems As New List(Of String)
    nameItems.Add(sSplit(i))
    nameItems.Add(sSplit(i + 1))
    nameItems.Add(sSplit(i + 2))
    nameItems.Add(sSplit(i + 3))
    names.Add(nameItems)
Next

' Turn the List(Of List(Of String)) into XML documents and save to the file system.
For Each name As List(Of String) In names
    Dim root As New XElement("Root", _
        New XElement(name(0),
                   New XElement(name(1)), _
                   New XElement(name(2)), _
                   New XElement(name(3)) _
                   ))
    root.Save("C:\Working Directory\" + name(0) + ".xml")
Next

Open in new window

0
 
vcharlesAuthor Commented:
Hi,

Can you please help me integrate code in Pat A with your latest code (Part B), assuming LinkFinal contains the following three tables, FCD,NA,NSC. I can't figure out how to use parts of the code from  Part A in Part B to access LinkFinal.

A.

 Dim xdoc = XElement.Load(Application.StartupPath & "\LinkFinal.xml")
        Dim tables = From t In xdoc.Descendants() _
                     Where t.Name.ToString().StartsWith("FCD")
                     Select t      
        For Each table In tables
            Dim fileNumber As String = table.Name.ToString()
            Dim newRoot = New XElement("DocumentElement", table)
            newRoot.Save(Application.StartupPath & "\" & fileNumber & ".xml")
        Next


B.

  ' Test input data
        Dim s = "FCD,NA,NSC"
        ' Split the input data into an array of strings
        Dim sSplit = s.Split(",")
        ' Assign every 4 elements to a list of string Representing one set of data
        Dim names As New List(Of List(Of String))

        ' Turn the array of strings to a List(Of List(Of String))
        For i As Integer = 0 To sSplit.Length - 1 Step 4
            Dim nameItems As New List(Of String)
            nameItems.Add(sSplit(i))
            nameItems.Add(sSplit(i + 1))
            nameItems.Add(sSplit(i + 2))
            nameItems.Add(sSplit(i + 3))
            names.Add(nameItems)
        Next

        ' Turn the List(Of List(Of String)) into XML documents and save to the file system.
        For Each name As List(Of String) In names
            Dim root As New XElement("Root", _
                New XElement(name(0),
                           New XElement(name(1)), _
                           New XElement(name(2)), _
                           New XElement(name(3)) _
                           ))
            root.Save(Application.StartupPath & "\" & name(0) & ".xml")
        Next

Thanks,
0
 
Fernando SotoRetiredCommented:
Hi Victor;

Part A and Part B have two completely different input types although producing the same XML output file structure. So I am not sure what you mean by integrating the two parts can you be a little bit more specific.
0
 
vcharlesAuthor Commented:
Hi,

I need to access LinkFinal and search the  tables using the string variable (i.e FCD,NA,NSC) to create the xml files instead of writing the same code for each table.

V.
0
 
Fernando SotoRetiredCommented:
Are you saying that you now want to search the results of Part A and Part B which are XML documents with the values from a comma separate string. If so which nodes in part A and Part B should look at seeming the node names in each document is different?
0
 
vcharlesAuthor Commented:
Hi,

Sorry for the confusion, I would like to create an xml file for each table in my xml file the initial code you provided me (code below) requires I write  the same code for each table, I was hoping there was a way to put the table names in a string variable and use the same code in part A to avoid writing duplicate code and changing the table names.


I thought that part of the code would cover all the tables in the xml file but it only works for the table name in include in StartsWith("Table").

Dim tables = From t in xdoc.Descendants() _
             Where t.Name.ToString().StartsWith("Table")
             Select t



complete code:

Dim xdoc = XElement.Load("C:\Working Directory\AllTables.xml")
' Get all the tableX nodes and there children
Dim tables = From t in xdoc.Descendants() _
             Where t.Name.ToString().StartsWith("Table")
             Select t

' Set up the new XML document and save to the file system            
For Each table In tables
    ' Get the Table number so that we can create the file name with that number
    Dim fileNumber As String = table.Name.ToString().SubString(5)
    ' Create a new Root node and add the TableX as its child
    Dim newRoot = New XElement("Root", table)
    ' Save the new XML document to the file system
    newRoot.Save("C:\Working Directory\File" + fileNumber + ".xml")
Next
0
 
Fernando SotoRetiredCommented:
Hi Victor;

You state, "I would like to create an xml file for each table in my xml file", so you have an XML file of which you wish to create multiple XML files from. This is what Part A does.

To your statement, "the initial code you provided me (code below) requires I write  the same code for each table", actually the code reads your original XML file and iterates through the nodes creating new XML files from them. All the code from Part A is need to creat 1 XML file. When this code completes one XML file was created. The code is then iterated over multiple times to create the remaining XML files that where parsed out of the original XML file. So there is no duplicate code in Part A

To your statement, "I was hoping there was a way to put the table names in a string variable and use the same code in part A to avoid writing duplicate code and changing the table names.", here I think you are talk about creating XML files from information given in a string variable but you wish to use Part A code to accomplish this. Well in Part A code you are reading an XML file into a XML document which is not a comma seperated string of node names as you state in Part B, the input is dissimilar and therefore cannot use the same code to accomplish your task, unless I have misunderstood you.

To your statement, "I thought that part of the code would cover all the tables in the xml file but it only works for the table name in include in StartsWith("Table")", In your original post you had an XML file with nodes as Table1, Table2, Table3 etc. and wanted to create individual XML files from those nodes and their children. In order to do that I needed to find a way to name the files so that you can find them easily in the directory. To do that I found the Table node and retrieved the number and I use that to create the file with and that is tthe reason for the need for StartsWith("Table"). If that is not the actual structure and names you need to state that we can only follow the information that you post.
0
 
vcharlesAuthor Commented:
Hi,

I used Table1,table2, Table3 as an example, but the actual tables names are  CTRY,NSN,NSC,FCI. When I used your code I used Where t.Name.ToString().StartsWith("CTRY") since it is the first table, didn't think the table names would impact the code.

Thanks,

Victor
0
 
Fernando SotoRetiredCommented:
OK, If you post a more accurate representation of the XML file you wish to parse and make smaller XML files from I will help re-write to handle that. please be specific.
0
 
vcharlesAuthor Commented:
OK, I will post an example of the xml file.
Thanks.
0
 
vcharlesAuthor Commented:
Hi,

Below is an example of the format of my xml file. I removed most of the data elements.

<?xml version="1.0" standalone="yes"?>
<DocumentElement>
  <CTRY>
    <Link_ID>1</Link_ID>
    <Receiver>1</Receiver>
  </CTRY>
  <NSN>
    <Link_ID>1</Link_ID>
   <NSN>1</NSN>
  </NSN>
  <NSC>
  </NSC>
  <FCI>
    <Link_ID>1</Link_ID>
  </FCI>
  <NA>
    <Link_ID>1</Link_ID
  </NA>

Thanks again for helping me solve this issue.

Victor
0
 
vcharlesAuthor Commented:
Thank you very much, will try it and get back to you tomorrow.
0
 
vcharlesAuthor Commented:
Thank You!
0
 
Fernando SotoRetiredCommented:
Not a problem, glad to help.
0
 
vcharlesAuthor Commented:
Hi FernandoSoto,

The code below works but the Root elements (<Root> </Root>) are missing how do I add the Roo elements?


' The directory name from which you will get the main XML file and where to save the smaler XML files.
Dim dirName As String = "C:\Working Directory\"
' Load the original XML file into memory
Dim xdoc As XDocument = XDocument.Load(dirName & "ParseToFiles.xml")

' The results of this query are the nodes to be saved into a there own file
Dim xFiles As List(Of XElement) = (From f In xdoc.Root.Elements()
                                   Select f).ToList()

' Enumerate list of nodes and save them to the filesystem
For Each node As XElement In xFiles
    Dim fileName = node.Name.ToString() & ".xml"
    node.Save(dirName & fileName)
Next

Thanks,

Victor
0
 
Fernando SotoRetiredCommented:
Hi Victor;

This will add the Root element to the XML.

' Enumerate list of nodes and save them to the filesystem
For Each node As XElement In xFiles
    Dim fileName = node.Name.ToString() & ".xml"
    Dim root As XElement = New XElement("Root", node)
    root.Save(dirName & fileName)
Next

Open in new window

0
 
vcharlesAuthor Commented:
It worked!

Thank You.

Victor
0
 
Fernando SotoRetiredCommented:
Not a problem Victor, glad to help.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.