Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Help with creating multiple xml files

Posted on 2013-10-28
21
Medium Priority
?
244 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 64

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 64

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
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 

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 64

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 64

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 64

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
 
LVL 64

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 64

Accepted Solution

by:
Fernando Soto earned 2000 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 64

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 64

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 64

Expert Comment

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

Featured Post

What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article describes relatively difficult and non-obvious issues that are likely to arise when creating COM class in Visual Studio and deploying it by professional MSI-authoring tools. It is assumed that the reader is already familiar with the cla…
In real business world data are crucial and sometimes data are shared among different information systems. Hence, an agreeable file transfer protocol need to be established.
Video by: ITPro.TV
In this episode Don builds upon the troubleshooting techniques by demonstrating how to properly monitor a vSphere deployment to detect problems before they occur. He begins the show using tools found within the vSphere suite as ends the show demonst…
Integration Management Part 2
Suggested Courses

963 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