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

c#, split, xml

Solution

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.

Problem

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.

Original source