Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Split an XML file into multiple XML Files based on nodes

Tags:

c#

split

xml

I have an XML file as follows

<?xml version="1.0>
<EMR>
  <CustomTextBox>
    <Text>WNL</Text>
    <Type>TextBox</Type>
    <Width>500</Width>
    <id>txt1</id>
  </CustomTextBox>

  <CustomTextBox>
    <Text>WNL</Text>
    <Type>TextBox</Type>
    <Width>500</Width>
    <id>txt2</id>
  </CustomTextBox>

  <AllControlsCount>
    <Width>0</Width>
    <id>ControlsID</id>
  </AllControlsCount>
</EMR>

I want to split the xml file int o three. According to its nodes

File 1:

<?xml version="1.0>
<CustomTextBox>
  <Text>WNL</Text>
  <Type>TextBox</Type>
  <Width>500</Width>
  <id>txt1</id>
</CustomTextBox>

File 2:

<?xml version="1.0>
<CustomTextBox>
  <Text>WNL</Text>
  <Type>TextBox</Type>
  <Width>500</Width>
  <id>txt2</id>
</CustomTextBox>

File 3:

<?xml version="1.0>
<AllControlsCount>
  <Width>0</Width>
  <id>ControlsID</id>
</AllControlsCount>

Also the nodes are dynamic, they may change. How can I split this xml file as multiple according to the nodes. If anybody knows please share.

like image 295
Nithesh Narayanan Avatar asked Dec 06 '22 09:12

Nithesh Narayanan


2 Answers

Try LinqToXml:

var xDoc = XDocument.Parse(Resource1.XMLFile1); // loading source xml
var xmls = xDoc.Root.Elements().ToArray(); // split into elements

for(int i = 0;i< xmls.Length;i++)
{
    // write each element into different file
    using (var file = File.CreateText(string.Format("xml{0}.xml", i + 1)))
    {
        file.Write(xmls[i].ToString());
    }
}

It will take all elements defined inside the root element and write its content into separate files.

like image 99
mipe34 Avatar answered Jan 23 '23 05:01

mipe34


With Linq to Xml its even simpler - you can use XElement.Save method to save any element to separate xml file:

XDocument xdoc = XDocument.Load(path_to_xml);
int index = 0;
foreach (var element in xdoc.Root.Elements())
    element.Save(++index + ".xml");

Or one line

XDocument.Load(path_to_xml).Root.Elements()
         .Select((e, i) => new { Element = e, File = ++i + ".xml" })
         .ToList().ForEach(x => x.Element.Save(x.File));
like image 21
Sergey Berezovskiy Avatar answered Jan 23 '23 05:01

Sergey Berezovskiy