F# Data: XML Type Provider
This article demonstrates how to use the XML Type Provider to access XML documents in a statically typed way. We first look at how the structure is inferred and then demonstrate the provider by parsing a RSS feed.
The XML Type Provider provides statically typed access to XML documents. It takes a sample document as an input (or document containing a root XML node with multiple child nodes that are used as samples). The generated type can then be used to read files with the same structure. If the loaded file does not match the structure of the sample, a runtime error may occur (but only when accessing e.g. non-existing element). Starting from version 3.0.0 there is also the option of using a schema (XSD) instead of relying on samples.
Introducing the provider
The type provider is located in the FSharp.Data.dll
assembly. Assuming the assembly
is located in the ../../bin
directory, we can load it in F# Interactive as follows:
(note we also need a reference to System.Xml.Linq
, because the provider uses the
XDocument
type internally):
1: 2: 3: |
|
Inferring type from sample
The XmlProvider<...>
takes one static parameter of type string
. The parameter can
be either a sample XML string or a sample file (relative to the current folder or online
accessible via http
or https
). It is not likely that this could lead to ambiguities.
The following sample generates a type that can read simple XML documents with a root node containing two attributes:
1: 2: 3: 4: |
|
The type provider generates a type Author
that has properties corresponding to the
attributes of the root element of the XML document. The types of the properties are
inferred based on the values in the sample document. In this case, the Name
property
has a type string
and Born
is int
.
XML is a quite flexible format, so we could represent the same document differently.
Instead of using attributes, we could use nested nodes (<name>
and <born>
nested
under <author>
) that directly contain the values:
1: 2: 3: 4: 5: |
|
The generated type provides exactly the same API for reading documents following this
convention (Note that you cannot use AuthorAlt
to parse samples that use the
first style - the implementation of the types differs, they just provide the same public API.)
The provider turns a node into a simply typed property only when the node contains just a primitive value and has no children or attributes.
Types for more complex structure
Now let's look at a number of examples that have more interesting structure. First of all, what if a node contains some value, but also has some attributes?
1: 2: 3: 4: |
|
If the node cannot be represented as a simple type (like string
) then the provider
builds a new type with multiple properties. Here, it generates a property Full
(based on the name of the attribute) and infers its type to be boolean. Then it
adds a property with a (special) name Value
that returns the content of the element.
Types for multiple simple elements
Another interesting case is when there are multiple nodes that contain just a
primitive value. The following example shows what happens when the root node
contains multiple <value>
nodes (note that if we leave out the parameter to the
Parse
method, the same text used for the schema will be used as the runtime value).
1: 2: 3: 4: |
|
The type provider generates a property Values
that returns an array with the
values - as the <value>
nodes do not contain any attributes or children, they
are turned into int
values and so the Values
property returns just int[]
!
Processing philosophers
In this section we look at an example that demonstrates how the type provider works
on a simple document that lists authors that write about a specific topic. The
sample document data/Writers.xml
looks as follows:
1: 2: 3: 4: |
|
At runtime, we use the generated type provider to parse the following string
(which has the same structure as the sample document with the exception that
one of the author
nodes also contains a died
attribute):
1: 2: 3: 4: 5: 6: |
|
When initializing the XmlProvider
, we can pass it a file name or a web URL.
The Load
and AsyncLoad
methods allows reading the data from a file or from a web resource. The
Parse
method takes the data as a string, so we can now print the information as follows:
1: 2: 3: 4: 5: 6: 7: 8: |
|
The value topic
has a property Topic
(of type string
) which returns the value
of the attribute with the same name. It also has a property Authors
that returns
an array with all the authors. The Born
property is missing for some authors,
so it becomes option<int>
and we need to print it using Option.iter
.
The died
attribute was not present in the sample used for the inference, so we
cannot obtain it in a statically typed way (although it can still be obtained
dynamically using author.XElement.Attribute(XName.Get("died"))
).
Global inference mode
In the examples shown earlier, an element was never (recursively) contained in an
element of the same name (for example <author>
never contained another <author>
).
However, when we work with documents such as XHTML files, this can often be the case.
Consider for example, the following sample (a simplified version of
data/HtmlBody.xml
):
1: 2: 3: 4: 5: 6: |
|
Here, a <div>
element can contain other <div>
elements and it is quite clear that
they should all have the same type - we want to be able to write a recursive function
that processes <div>
elements. To make this possible, you need to set an optional
parameter Global
to true
:
1: 2: |
|
When the Global
parameter is true
, the type provider unifies all elements of the
same name. This means that all <div>
elements have the same type (with a union
of all attributes and all possible children nodes that appear in the sample document).
The type is located under a type Html
, so we can write a printDiv
function
that takes Html.Div
and acts as follows:
1: 2: 3: 4: 5: 6: 7: 8: 9: |
|
The function first prints all text included as <span>
(the element never has any
attributes in our sample, so it is inferred as string
), then it recursively prints
the content of all <div>
elements. If the element does not contain nested elements,
then we print the Value
(inner text).
Loading Directly from a File or URL
In many cases we might want to define schema using a local sample file, but then directly
load the data from disk or from a URL either synchronously (with Load
) or asynchronously
(with AsyncLoad
).
For this example I am using the US Census data set from https://api.census.gov/data.xml
, a sample of
which I have used here for ../data/Census.xml
. This sample is greatly reduced from the live data, so
that it contains only the elements and attributes relevant to us:
1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: |
|
When doing this for your scenario, be careful to ensure that enough data is given for the provider
to infer the schema correctly. For example, the first level <dct:dataset>
element must be included at
least twice for the provider to infer the Datasets
array rather than a single Dataset
object.
1: 2: 3: 4: 5: 6: |
|
This US Census data is an interesting dataset with this top level API returning hundreds of other datasets each with their own API. Here we use the Census data to get a list of titles and URLs for the lower level APIs.
Bringing in Some Async Action
Let's go one step further and assume here a sligthly contrived but certainly plausible example where we cache the Census URLs and refresh once in a while. Perhaps we want to load this in the background and then post each link over (for example) a message queue.
This is where AsyncLoad
comes into play:
1: 2: 3: 4: 5: 6: 7: 8: 9: 10: |
|
Reading RSS feeds
To conclude this introduction with a more interesting example, let's look how to parse a RSS feed. As discussed earlier, we can use relative paths or web addresses when calling the type provider:
1:
|
|
This code builds a type Rss
that represents RSS feeds (with the features that are used
on http://tomasp.net
). The type Rss
provides static methods Parse
, Load
and AsyncLoad
to construct it - here, we just want to reuse the same URI of the schema, so we
use the GetSample
static method:
1:
|
|
Printing the title of the RSS feed together with a list of recent posts is now quite
easy - you can simply type blog
followed by .
and see what the autocompletion
offers. The code looks like this:
1: 2: 3: 4: 5: 6: |
|
Transforming XML
In this example we will now also create XML in addition to consuming it. Consider the problem of flattening a data set. Let's say you have xml data that looks like this:
1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: |
|
and you want to transform it into something like this:
1: 2: 3: 4: 5: 6: 7: 8: |
|
We'll create types from both the input and output samples and use the constructors on the types generated by the XmlProvider:
1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: |
|
Using a schema (XSD)
The Schema
parameter can be used (instead of Sample
) to specify an XML schema.
The value of the parameter can be either the name of a schema file or plain text
like in the following example:
1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: |
|
The properties of the provided type are derived from the schema instead of being inferred from samples.
Usually a schema is not specified as plain text but stored in a file like
data/po.xsd
and the uri is set in the Schema
parameter:
1:
|
|
When the file includes other schema files, the ResolutionFolder
parameter can help locating them.
The uri may also refer to online resources:
1:
|
|
The schema is expected to define a root element (a global element with complex type). In case of multiple root elements:
1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: |
|
the provided type has an optional property for each alternative:
1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: |
|
Common XSD constructs: sequence and choice
A sequence
is the most common way of structuring elements in a schema.
The following xsd defines foo
as a sequence made of an arbitrary number
of bar
elements followed by a single baz
element.
1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: |
|
here a valid xml element is parsed as an instance of the provided type, with two properties corresponding to bar
and baz
elements, where the former is an array in order to hold multiple elements:
1: 2: 3: 4: 5: 6: 7: 8: 9: 10: |
|
Instead of a sequence we may have a choice
:
1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: |
|
although a choice is akin to a union type in F#, the provided type still has
properties for bar
and baz
directly available on the foo
object; in fact
the properties representing alternatives in a choice are simply made optional
(notice that for arrays this is not even necessary because an array can be empty).
This decision is due to technical limitations (discriminated unions are not supported
in type providers) but also preferred because it improves discoverability:
intellisense can show both alternatives. There is a lack of precision but this is not the main goal.
1: 2: 3: 4: 5: 6: 7: 8: 9: |
|
Another xsd construct to model the content of an element is all
, which is used less often and
it's like a sequence where the order of elements does not matter. The corresponding provided type
in fact is essentially the same as for a sequence.
Advanced schema constructs
XML Schema provides various extensibility mechanisms. The following example is a terse summary mixing substitution groups with abstract recursive definitions.
1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: |
|
Substitution groups are like choices, and the type provider produces an optional property for each alternative.
Validation
The GetSchema
method on the generated type returns an instance
of System.Xml.Schema.XmlSchemaSet
that can be used to validate documents:
1: 2: 3: |
|
The Validate
method accepts a callback to handle validation issues;
passing null
will turn validation errors into exceptions.
There are overloads to allow other effects (for example setting default values
by enabling the population of the XML tree with the post-schema-validation infoset;
for details see the documentation).
Remarks on using a schema
The XML Type Provider supports most XSD features.
Anyway the XML Schema specification is rich and complex and also provides a
fair degree of openness
which may be difficult to handle in
data binding tools; but in F# Data, when providing typed views on elements becomes too challenging
(take for example wildcards) the underlying XElement
is still available.
An important design decision is to focus on elements and not on complex types; while the latter
may be valuable in schema design, our goal is simply to obtain an easy and safe way to access xml data.
In other words the provided types are not intended for domain modeling (it's one of the very few cases
where optional properties are preferred to sum types).
Hence, we do not provide types corresponding to complex types in a schema but only corresponding
to elements (of course the underlying complex types still affect the shape of the provided types
but this happens only implicitly).
Focusing on element shapes let us generate a type that should be essentially the same as one
inferred from a significant set of valid samples. This allows a smooth transition (replacing Sample
with Schema
)
when a schema becomes available.
Related articles
- Using JSON provider in a library also applies to XML type provider
- API Reference: XmlProvider type provider
- API Reference: XElementExtensions module
namespace FSharp
--------------------
namespace Microsoft.FSharp
namespace FSharp.Data
--------------------
namespace Microsoft.FSharp.Data
<summary>Typed representation of a XML file.</summary>
<param name='Sample'>Location of a XML sample file or a string containing a sample XML document.</param>
<param name='SampleIsList'>If true, the children of the root in the sample document represent individual samples for the inference.</param>
<param name='Global'>If true, the inference unifies all XML elements with the same name.</param>
<param name='Culture'>The culture used for parsing numbers and dates. Defaults to the invariant culture.</param>
<param name='Encoding'>The encoding used to read the sample. You can specify either the character set name or the codepage number. Defaults to UTF8 for files, and to ISO-8859-1 the for HTTP requests, unless `charset` is specified in the `Content-Type` response header.</param>
<param name='ResolutionFolder'>A directory that is used when resolving relative file references (at design time and in hosted execution).</param>
<param name='EmbeddedResource'>When specified, the type provider first attempts to load the sample from the specified resource
(e.g. 'MyCompany.MyAssembly, resource_name.xml'). This is useful when exposing types generated by the type provider.</param>
<param name='InferTypesFromValues'>If true, turns on additional type inference from values.
(e.g. type inference infers string values such as "123" as ints and values constrained to 0 and 1 as booleans. The XmlProvider also infers string values as JSON.)</param>
<param name='Schema'>Location of a schema file or a string containing xsd.</param>
Parses the specified XML string
from Microsoft.FSharp.Collections
Parses the specified XML string
from Microsoft.FSharp.Core
type Html = XmlProvider<...>
--------------------
type HtmlAttribute =
private | HtmlAttribute of name: string * value: string
static member New : name:string * value:string -> HtmlAttribute
Prints the content of a <div> element
inherit XmlElement
new : id: Option<string> * value: Option<string> * spans: string [] * divs: Div [] -> Div + 1 overload
member Divs : Div []
member Id : Option<string>
member Spans : string []
member Value : Option<string>
Loads XML from the specified uri
XmlProvider<...>.Load(reader: System.IO.TextReader) : XmlProvider<...>.CensusApi
Loads XML from the specified reader
XmlProvider<...>.Load(stream: System.IO.Stream) : XmlProvider<...>.CensusApi
Loads XML from the specified stream
from Microsoft.FSharp.Collections
Loads XML from the specified uri
type LiteralAttribute =
inherit Attribute
new : unit -> LiteralAttribute
--------------------
new : unit -> LiteralAttribute
inherit XmlElement
new : orderLines: OrderLine [] -> OrderLines + 1 overload
member OrderLines : OrderLine []
inherit XmlElement
new : customer: string * order: string * item: string * quantity: int -> OrderLine + 1 overload
member Customer : string
member Item : string
member Order : string
member Quantity : int
Parses the specified XSD string
Parses the specified XSD string
Parses the specified XSD string
Parses the specified XSD string
(extension) System.Xml.Linq.XDocument.Validate(schemas: XmlSchemaSet, validationEventHandler: ValidationEventHandler, addSchemaInfo: bool) : unit