Solved

Help with creating multiple xml files

Posted on 2013-10-28
21
233 Views
Last Modified: 2013-11-04
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
0
Comment
Question by:vcharles
  • 11
  • 10
21 Comments
 
LVL 62

Expert Comment

by:Fernando Soto
ID: 39605756
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
 

Author Comment

by:vcharles
ID: 39605983
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
 
LVL 62

Expert Comment

by:Fernando Soto
ID: 39606492
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
 

Author Comment

by:vcharles
ID: 39607836
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
 
LVL 62

Expert Comment

by:Fernando Soto
ID: 39609421
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
 

Author Comment

by:vcharles
ID: 39610207
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
 
LVL 62

Expert Comment

by:Fernando Soto
ID: 39610662
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
 

Author Comment

by:vcharles
ID: 39610820
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
 
LVL 62

Expert Comment

by:Fernando Soto
ID: 39611605
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
 

Author Comment

by:vcharles
ID: 39611877
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
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 62

Expert Comment

by:Fernando Soto
ID: 39612043
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
 

Author Comment

by:vcharles
ID: 39612057
OK, I will post an example of the xml file.
Thanks.
0
 

Author Comment

by:vcharles
ID: 39612205
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
 
LVL 62

Accepted Solution

by:
Fernando Soto earned 500 total points
ID: 39615079
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
 

Author Comment

by:vcharles
ID: 39615408
Thank you very much, will try it and get back to you tomorrow.
0
 

Author Closing Comment

by:vcharles
ID: 39619757
Thank You!
0
 
LVL 62

Expert Comment

by:Fernando Soto
ID: 39619821
Not a problem, glad to help.
0
 

Author Comment

by:vcharles
ID: 39622543
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
 
LVL 62

Expert Comment

by:Fernando Soto
ID: 39622697
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
 

Author Comment

by:vcharles
ID: 39622754
It worked!

Thank You.

Victor
0
 
LVL 62

Expert Comment

by:Fernando Soto
ID: 39622805
Not a problem Victor, glad to help.
0

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

This document covers how to connect to SQL Server and browse its contents.  It is meant for those new to Visual Studio and/or working with Microsoft SQL Server.  It is not a guide to building SQL Server database connections in your code.  This is mo…
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now