F# XML Type Provider Common Elements

偶尔善良 提交于 2019-12-06 02:57:39

The XML type provider works the best in the case when your inputs are fairly regular. So, if you need to process multiple different schemas, it might be better to use the standard XML tools (like XDocument).

That said, you can use a few tricks that make your scenario nicer. First, you can specify a list of samples. To do that, just create a XML file that has some (any) root and both of your samples:

<?xml version="1.0" encoding="utf-8"?>
<samples>
  <root>
    <description><author> Me </author></description>
    <element > Data </element>
    <otherelement> Data </otherelement>
  </root>
  <root2>
    <description ><author> Me </author></description>
    <elem > Data </elem>
    <diffelem> Data </diffelem >
  </root2>
</samples>

Now you can create XML type provider and tell it that your sample file is a list (SampleIsList=true) and that it should use global resolution (meaning that all elements named description will be treated as values of the same type):

type X = XmlProvider<"C:/temp/sample1.xml", SampleIsList=true, Global=true>

Now, you have differently named roots, which makes the situation trickier, but you can now write code that gets the <description> element from one or the other root:

let i = X.Load("...")

let description = 
  match i.Root, i.Root2 with
  | Some r1, _ -> r1.Description
  | _, Some r2 -> r2.Description
  | _ -> failwith "Missing"

This gives you a description node with author sub node that you can get for both of your documents:

description.Author
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!