I have an XML file and I\'m inferring its XSD schema in run-time, using the XmlSchemaInference
class.
Sample file:
Okay! No answer and not much interest - I figured it out on my own.
I used code from this MSDN article I googled up: Traversing XML Schemas
And I based my recursive solution on it.
void PrintSchema(string xmlFilePath)
{
var schemaSet = new XmlSchemaInference().InferSchema(XmlReader.Create(xmlFilePath));
foreach (XmlSchemaElement element in schemaSet
.Schemas()
.Cast<XmlSchema>()
.SelectMany(s => s.Elements.Values.Cast<XmlSchemaElement>()))
{
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);
}
}
The output is:
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)
I leave to you to judge how friendly this API is, especially given how scarce is the MSDN documentation on these particular classes. Any comments or insights are appreciated.