How to split an XML file into multiple XML files

I am trying to split an XML file into several small xml files in C # .net and am trying to get the best possible approach to this. Any help on this would be a great example ... An example of what I'm trying to do ...

XML source document

<?xml version="1.0" standalone="yes"?> <DATABASE> <DOC> <DOCID>8510188</DOCID> <ISSUE>2010</ISSUE> <CAT>Literature and Art</CAT> <TITLE>Test</TITLE> <TEXT>Test</TEXT> </DOC> <DOC> <DOCID>1510179</DOCID> <ISSUE>2012</ISSUE> <CAT>Miscellaneous</CAT> <TITLE>Test</TITLE> <TEXT>Test</TEXT> </DOC> </DATABASE> 

Should break into two xml documents as shown below

one)

 <?xml version="1.0" standalone="yes"?> <DATABASE> <DOC> <DOCID>8510188</DOCID> <ISSUE>2010</ISSUE> <CAT>Literature and Art</CAT> <TITLE>Test</TITLE> <TEXT>Test</TEXT> </DOC> </DATABASE> 

2)

 <?xml version="1.0" standalone="yes"?> <DATABASE> <DOC> <DOCID>1510179</DOCID> <ISSUE>2012</ISSUE> <CAT>Miscellaneous</CAT> <TITLE>Test</TITLE> <TEXT>Test</TEXT> </DOC> </DATABASE> 
+8
split c # xml
source share
1 answer

Well, I would use LINQ to XML:

 XDocument doc = XDocument.Load("test.xml"); var newDocs = doc.Descendants("DOC") .Select(d => new XDocument(new XElement("DATABASE", d))); foreach (var newDoc in newDocs) { newDoc.Save(/* work out filename here */); } 

(I assume that you want to save them. Perhaps you do not need it. I tested this by simply printing them to the console.)

+7
source share

All Articles