You can manipulate an XML file by using XPath, XQuery and XSLT, but you need to study those stuffs first before you can use them. And also, creating an in-memory XML is very cumbersome. For example, I'm going to create this XML:

I'll show you a common way of creating this XML if I'm going to use the XmlDocument object of the DOM (Document Object Model) by Microsoft. I'll be leaning towards the C# implementation for this because I'm more familiar with it. Here it is:


Notice that by indenting the code construct, the XML tree show you the underlying XML. The functional construction gives you a powerful approach when you're creating XML elements, it lets you create the whole XML construct with just one statement.
Another feature that I like to include here is the Language Integrated Query for XML, that's why it's LINQ. LINQ provides you a consistent experience of querying across different data models. I'll be showing a sample query for LINQ to XML:

The object returnXDoc will have the root elemet "student", then have the child nodes "name" and "phone" from the sample XML I showed above.
Query expressions provide an ease-of-use layer on top of the underlying explicit dot notation similar to the way that foreach is an ease-of-use mechanism that consists of a call to GetEnumerator() and a while loop. When working with XML, you will probably find both approaches useful.
There are methods that returns an IEnumerable<object> type, you can manipulate XML (add, update or remove an element/node) and it gives you the in-line queries. Just explore this new API, LINQ to XML is very flexible and it will provide you with a modularized, simple and optimized contruct in developing applications that involves XML.
No comments:
Post a Comment