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.
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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With