Home Random Page


CATEGORIES:

BiologyChemistryConstructionCultureEcologyEconomyElectronicsFinanceGeographyHistoryInformaticsLawMathematicsMechanicsMedicineOtherPedagogyPhilosophyPhysicsPolicyPsychologySociologySportTourism






Task 4 – Transforming XML Output

This task walks though transforming the output of your previous query into a new XML document.

Suppose you wanted to create a new xml file that only contained those customers located in London. In this task you write this to a different structure than the Customers.xml file; each customer element stores the city and name as descendent elements rather than attributes.

 

1. Add the following code that iterates through the results and stores them in this new format.

public static void XMLQuery()

{

XDocument doc = XDocument.Load("Customers.xml");

 

var results = from c in doc.Descendants("Customer")

where c.Attribute("City").Value == "London"

select c;

XElement transformedResults =

new XElement("Londoners",

from customer in results

select new XElement("Contact",

new XAttribute("ID", customer.Attribute("CustomerID").Value),

new XElement("Name", customer.Attribute("ContactName").Value),

new XElement("City", customer.Attribute("City").Value)));

 

Console.WriteLine("Results:\n{0}", transformedResults);

}

 

Here a temporary variable, results, was used to store the information returned from the query before altering the structure of the returned data.

2. Press Ctrl+F5 to build and run the application. The new XML document is printed. Notice the same data is returned, just structured differently. Press any key to terminate the application.

3. Save the output to a file allowing the results of the query to be exported. To do this add the following line of code.

public static void XMLQuery()

{

XDocument doc = XDocument.Load("Customers.xml");

 

var results = from c in doc.Descendants("Customer")

where c.Attribute("City").Value == "London"

select c;

XElement transformedResults =

new XElement("Londoners",

from customer in results

select new XElement("Contact",

new XAttribute("ID", customer.Attribute("CustomerID").Value),

new XElement("Name", customer.Attribute("ContactName").Value),

new XElement("City", customer.Attribute("City").Value)));

 

Console.WriteLine("Results:\n{0}", transformedResults);

transformedResults.Save("Output.xml");

}

4. Press Ctrl+F5 to build and run the application. The new XML document is printed to the screen and written to a file that can be located where you placed your Customers.xml file. Now the data can be exported as XML to another application. Last, press any key to terminate the application.


Date: 2015-02-03; view: 705


<== previous page | next page ==>
Task 2 – Querying by Reading in an XML File | Task 4 – Querying a DataSet
doclecture.net - lectures - 2014-2024 year. Copyright infringement or personal data (0.005 sec.)