In F# I would like to do something like this.
let xml = XDocument.Load(url);
The xml could be dynamically parsed and I would get the xml tree available in intellisense.
let products = xml.root.products;
arrays could be filterable while values and attributes directly available
let productSoap = xml.root.products.Where(o => o.productName == "Soap");
let documentName = xml.root.Docu开发者_JAVA技巧mentName;
Why do I need to use System.Xml and System.Xml.Linq in a functional language to parse xml?
The comments below are correct, you will unfortunately need to wait for F#'s Type Providers features in order to do this at 'develop time'. (So that F#'s IntelliSense will do the XML parsing and provide you with data while you are writing your code.)
However, in the mean time you can use the XSD.exe tool to generate a .NET library wrapping an XML document. See a quick tutorial here.
The workflow is you:
- Feed an XML document to xsd.exe
- XSD.exe will output an assembly which can load/strongly type that XML document
IIRC, xsd.exe was written long before LINQ and more 'modern' .NET features, so the generated object model is a little clunky. However, it is better than just parsing the document yourself and using XPath to blindly query into the data.
Here's a code snippet from the tutorial:
StreamReader str = new StreamReader("cd_catalog.xml");
XmlSerializer xSerializer = new XmlSerializer(typeof(CATALOG));
CATALOG myCdCatalogue = (CATALOG)xSerializer.Deserialize(str);
foreach (CATALOG.CDRow cd in myCdCatalogue.CD)
{
Console.WriteLine(cd.TITLE);
Console.WriteLine(cd.ARTIST);
Console.WriteLine(cd.COUNTRY);
Console.WriteLine(cd.COMPANY);
Console.WriteLine(cd.PRICE);
Console.WriteLine(cd.YEAR);
Console.WriteLine();
}
str.Close();
精彩评论