开发者

could i get the xml tree available as intellisense in functional languages?

开发者 https://www.devze.com 2023-02-01 17:28 出处:网络
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.

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:

  1. Feed an XML document to xsd.exe
  2. 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();
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号