He visto preguntas similares hechas en el pasado (la revelación completa, he pedir a un question similares a mí mismo). Analizar un XSD no es para los débiles de corazón.
Básicamente tiene 2 opciones, primero es más fácil de implementar, pero se puede romper más fácilmente mediante cambios menores en el XSD. el segundo es más robusto pero difícil de implementar.
Opción 1:
Analizar el XSD con LINQ (u otro C# analizador XML si lo prefiere). Como un XSD es solo un XML, puede cargarlo en un XDocument
y simplemente leerlo a través de LINQ.
Por tan sólo una muestra de su propia XSD:
<xsd:simpleType name="Amount_Type">
<xsd:annotation>
<xsd:documentation>Amount</xsd:documentation>
</xsd:annotation>
<xsd:restriction base="xsd:string">
<xsd:maxLength value="12" />
</xsd:restriction>
</xsd:simpleType>
Puede acceder a la MaxLength:
var xDoc = XDocument.Load("your XSD path");
var ns = XNamespace.Get(@"http://www.w3.org/2001/XMLSchema");
var length = (from sType in xDoc.Element(ns + "schema").Elements(ns + "simpleType")
where sType.Attribute("name").Value == "Amount_Type"
from r in sType.Elements(ns + "restriction")
select r.Element(ns + "maxLength").Attribute("value")
.Value).FirstOrDefault();
Esto no ofrece un método muy fácil para el análisis por el nombre del tipo, especialmente para extenderse tipos. Para usar esto necesitas saber la ruta exacta para cada elemento que estás buscando.
Opción 2:
Esto es demasiado complejo para una respuesta rápida (Nota: véase la edición abajo - Tenía algo de tiempo y poner juntos una solución de trabajo), así que voy a alentar a mirar mi propia pregunta que he vinculado anteriormente. En él, conecté un great blog que muestra cómo dividir seriamente el XSD en pedazos y podría permitirle realizar el tipo de búsqueda que desea. Tienes que decidir si vale la pena el esfuerzo para desarrollarlo (el blog muestra una implementación con XmlReader
que contiene un XML validado contra el XSD en cuestión, pero puedes lograrlo cargando directamente el XSD y analizándolo).
2 idea clave para encontrar en el blog son:
// in the getRestriction method (reader in this context is an `XmlReader` that
// contains a XML that is being validated against the specific XSD
if (reader.SchemaInfo.SchemaElement == null) return null;
simpleType = reader.SchemaInfo.SchemaElement.ElementSchemaType as XmlSchemaSimpleType;
if (simpleType == null) return null;
restriction = simpleType.Content as XmlSchemaSimpleTypeRestriction;
// then in the getMaxLength method
if (restriction == null) return null;
List<int> result = new List<int>();
foreach (XmlSchemaObject facet in restriction.Facets) {
if (facet is XmlSchemaMaxLengthFacet) result.Add(int.Parse(((XmlSchemaFacet) facet).Value));
He intentado lo mismo el año pasado para analizar un XSD como parte de un método de validación de datos complicada. Me llevó la mayor parte de una semana comprender realmente lo que sucedía y adaptar los métodos del blog para adaptarme a mis propósitos. Definitivamente es la mejor manera de implementar exactamente lo que desea.
Si desea probar esto con un esquema independiente, puede cargar el XSD en un objeto XmlSchemaSet
, luego use la propiedad GlobalTypes
para encontrar el tipo específico que está buscando.
EDIT: llegué a mi viejo código y comenzó la elaboración de un código para ayudarte.
En primer lugar para cargar su esquema:
XmlSchemaSet set; // this needs to be accessible to the methods below,
// so should be a class level field or property
using (var fs = new FileStream(@"your path here", FileMode.Open)
{
var schema = XmlSchema.Read(fs, null);
set = new XmlSchemaSet();
set.Add(schema);
set.Compile();
}
Los siguientes métodos deben dar cierra a lo que quiere basado en el XSD que ya ha proporcionado. Debería ser bastante adaptable para tratar con estructuras más complejas.
public Dictionary<string, int> GetElementMaxLength(String xsdElementName)
{
if (xsdElementName == null) throw new ArgumentException();
// if your XSD has a target namespace, you need to replace null with the namespace name
var qname = new XmlQualifiedName(xsdElementName, null);
// find the type you want in the XmlSchemaSet
var parentType = set.GlobalTypes[qname];
// call GetAllMaxLength with the parentType as parameter
var results = GetAllMaxLength(parentType);
return results;
}
private Dictionary<string, int> GetAllMaxLength(XmlSchemaObject obj)
{
Dictionary<string, int> dict = new Dictionary<string, int>();
// do some type checking on the XmlSchemaObject
if (obj is XmlSchemaSimpleType)
{
// if it is a simple type, then call GetMaxLength to get the MaxLength restriction
var st = obj as XmlSchemaSimpleType;
dict[st.QualifiedName.Name] = GetMaxLength(st);
}
else if (obj is XmlSchemaComplexType)
{
// if obj is a complexType, cast the particle type to a sequence
// and iterate the sequence
// warning - this will fail if it is not a sequence, so you might need
// to make some adjustments if you have something other than a xs:sequence
var ct = obj as XmlSchemaComplexType;
var seq = ct.ContentTypeParticle as XmlSchemaSequence;
foreach (var item in seq.Items)
{
// item will be an XmlSchemaObject, so just call this same method
// with item as the parameter to parse it out
var rng = GetAllMaxLength(item);
// add the results to the dictionary
foreach (var kvp in rng)
{
dict[kvp.Key] = kvp.Value;
}
}
}
else if (obj is XmlSchemaElement)
{
// if obj is an XmlSchemaElement, the you need to find the type
// based on the SchemaTypeName property. This is why your
// XmlSchemaSet needs to have class-level scope
var ele = obj as XmlSchemaElement;
var type = set.GlobalTypes[ele.SchemaTypeName];
// once you have the type, call this method again and get the dictionary result
var rng = GetAllMaxLength(type);
// put the results in this dictionary. The difference here is the dictionary
// key is put in the format you specified
foreach (var kvp in rng)
{
dict[String.Format("{0}/{1}", ele.QualifiedName.Name, kvp.Key)] = kvp.Value;
}
}
return dict;
}
private Int32 GetMaxLength(XmlSchemaSimpleType xsdSimpleType)
{
// get the content of the simple type
var restriction = xsdSimpleType.Content as XmlSchemaSimpleTypeRestriction;
// if it is null, then there are no restrictions and return -1 as a marker value
if (restriction == null) return -1;
Int32 result = -1;
// iterate the facets in the restrictions, look for a MaxLengthFacet and parse the value
foreach (XmlSchemaObject facet in restriction.Facets)
{
if (facet is XmlSchemaMaxLengthFacet)
{
result = int.Parse(((XmlSchemaFacet)facet).Value);
break;
}
}
return result;
}
A continuación, el uso es bastante simple, sólo tiene que llamar al método GetElementMaxLength(String)
y ha de devolver un diccionario de los nombres en el formato que se proporciona con el valor que la longitud máxima:
var results = GetElementMaxLength("Setup_Type");
foreach (var item in results)
{
Console.WriteLine("{0} | {1}", item.Key, item.Value);
}
Gracias a todos por las excelentes soluciones. Fue muy útil mirar el código. Hasta ahora, he probado la solución de @ psubsee2003 y está funcionando muy bien para mí. – Jyina