从XML文件推断出XmlSchema – 如何遍历XSD中的所有元素?
我有一个XML文件,我在运行时使用XmlSchemaInference
类推断其XSD架构。
示例文件:
10 25 50
它确实有效 – 它很好地推断了架构:
问题是:
如何遍历(递归?)遍历此模式中的所有元素? 它们是如何由XmlSchemaSet
类存储的? 我需要将它们呈现给用户,以便他们可以进行一些映射。
我正在从XmlSchemaSet.Schemas
属性中检索XmlSchema
,然后是什么? XmlSchema.Elements
只包含一个项目( products
),我找不到任何方法来查找其子元素。
好的! 没有答案也没有太多兴趣 – 我自己想出来了。
我使用了这篇MSDN文章中的代码我搜索过: 遍历XML Schema
我基于它的递归解决方案。
void PrintSchema(string xmlFilePath) { var schemaSet = new XmlSchemaInference().InferSchema(XmlReader.Create(xmlFilePath)); foreach (XmlSchemaElement element in schemaSet .Schemas() .Cast() .SelectMany(s => s.Elements.Values.Cast())) { Debug.WriteLine(element.Name + " (element)"); IterateOverElement(element.Name, element); } } void IterateOverElement(string root, XmlSchemaElement element) { var complexType = element.ElementSchemaType as XmlSchemaComplexType; if (complexType == null) { return; } if (complexType.AttributeUses.Count > 0) { var enumerator = complexType.AttributeUses.GetEnumerator(); while (enumerator.MoveNext()) { var attribute = (XmlSchemaAttribute)enumerator.Value; Debug.WriteLine(root + "." + attribute.Name + " (attribute)"); } } var sequence = complexType.ContentTypeParticle as XmlSchemaSequence; if (sequence == null) { return; } foreach (XmlSchemaElement childElement in sequence.Items) { root += String.Concat(".", childElement.Name); Debug.WriteLine(root + " (element)"); // recursion IterateOverElement(root, childElement); } }
输出是:
products (element) products.product (element) products.product.id (attribute) products.product.name (attribute) products.product.size (element) products.product.size.name (attribute) products.product.price (element) products.product.price.net (element) products.product.price.gross (element)
我留给你判断这个API是多么友好,特别是鉴于这些特定类的MSDN文档有多么稀缺。 任何意见或见解表示赞赏。