Read an XML file between a repetative nodes and create new xml files from it

I have an xml file. Here I need to read the elements between ImportDocument starting and ending nodes and create a new xml document with those elements and its values. So, for the below xml file, I need to create 3 new xml files.

But before creating a new xml document I need to get values from database for Pernsr and SubmittingPernr element values.

Can anyone has any sample code for this task?

<?xml version="1.0" encoding="UTF-8"?>
-<DmHrImport xsi:noNamespaceSchemaLocation=""
      <FilePath>\files\0000\00895722_1_Emergency Contact Information.pdf</FilePath>
      <FilePath>\files\0000\00895722_2_Release of Info & Documentation(College).pdf</FilePath>
      <FilePath>\files\0000\00891102_3_Emergency Contact Information.pdf</FilePath>
Who is Participating?
Fernando SotoConnect With a Mentor RetiredCommented:
Hi pothireddysunil;

The following sample code should get you started.

// Load the XML file to be parsed into the system memory
var xdoc = XDocument.Load("C:/Working Directory/Export.xml");

// Query the XML document for all the ImportDocument elements and its child nodes 
// and place it into a List<XElement>
var results = (from node in xdoc.Root.Descendants("ImportDocument")
               select node).ToList();

// index is here to give the file names a unique name
int index = 1;
// Iterate over the List<XElement> that holds the ImportDocument nodes
foreach (XElement node in results)
    // Create a new XDocument and add the node as the Root node of the new document
    var doc = new XDocument(node);
    // Get the following two values from the XML to query database
    string Pernr = node.Element("Pernr").Value;
    string SubmittingPernr = node.Element("SubmittingPernr").Value;
    // Query the database and any other thing that needs to be done
    // I am creating a file name here, please change as needed
    string saveAs = @"C:\Working Directory\" + Pernr + "-" + index.ToString() + ".xml";
    // Save the new document to the file system

Open in new window

I suspect this is some kind of batch process and importdocument tags would be in good numbers.
Pernr and SubmittingPernr are look up values

My approach would be -
1. Query database and spit out an xml which will server as lookup xml.
2. Use XSLT to break batch xml file into multiple xml files.

Below url's should help you in achieving #2.

pothireddysunilAuthor Commented:
Fernando SotoRetiredCommented:
Not a problem, glad I was able to help.
All Courses

From novice to tech pro — start learning today.