Tuesday, 4 March 2014

.Net Tips : Create XML file from another XML file with selected Elements using LINQ with C#.Net and VB.Net example

You can create XML file from another file with selected elements from source XML file using LINQ. In this, we query the source XML file using LINQ and write or create new XML file.

Here is example for this. 
In this example we take one "Book.xml" file. In this file we have element like Title, Pages, ISBN and Auther. Now we are querying the "Book.xml" file to get only Title and ISBN of book and create another XML with data that contains only Title and ISBN element.


C#. Net Example :
        XDocument objDoc = XDocument.Load((Server.MapPath("Books.xml")));
        
        var objResults = new XElement("Results",
                         from b in objDoc.Element("Books").Elements("Book")
                         from t in b.Elements("Title")
                         from a in b.Elements("ISBN")
                         select new XElement("Result", t, a));

        StringWriter objSW = new StringWriter();

        //save to XmlWriter
        System.Xml.XmlWriterSettings objSettings = new System.Xml.XmlWriterSettings();
        objSettings.Indent = true;

        XDocument objNewDoc = new XDocument();
        System.Xml.XmlWriter objXMLWriter = System.Xml.XmlWriter.Create(objSW, objSettings);

        objResults.Save(objXMLWriter);
        
        objXMLWriter.Close();
        //Console.WriteLine(objSW.ToString());

        //save to file
        objResults.Save(Server.MapPath("Results.xml"));

VB.Net Examples :
        Dim objDoc As XDocument = XDocument.Load((Server.MapPath("Books.xml")))

        Dim objResults = New XElement("Results",
                                      From b In objDoc.Element("Books").Elements("Book")
                                      From t In b.Elements("Title") From a In b.Elements("ISBN") Select New XElement("Result", t, a))

        Dim objSW As New StringWriter()

        'save to XmlWriter
        Dim objSettings As New System.Xml.XmlWriterSettings()
        objSettings.Indent = True

        Dim objNewDoc As New XDocument()
        Dim objXMLWriter As System.Xml.XmlWriter = System.Xml.XmlWriter.Create(objSW, objSettings)

        objResults.Save(objXMLWriter)

        objXMLWriter.Close()
        'Console.WriteLine(objSW.ToString());

        'save to file
        objResults.Save(Server.MapPath("Results.xml"))

Output :


Below are the books that you would like :

1 comment: