Обход XML-схем не удался

1

Я хочу проанализировать всю информацию/элементы из xml-схемы (xsd) и работать с ними в качестве переменных в моей программе. Я нашел эту статью от Microsoft: http://msdn.microsoft.com/en-us/library/ms255932.aspx

Пример кода из Microsoft

using System;
using System.Collections;
using System.Xml;
using System.Xml.Schema;

class XmlSchemaTraverseExample
{
    static void Main()
    {
        // Add the customer schema to a new XmlSchemaSet and compile it. 
        // Any schema validation warnings and errors encountered reading or  
        // compiling the schema are handled by the ValidationEventHandler delegate.
        XmlSchemaSet schemaSet = new XmlSchemaSet();
        schemaSet.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
        schemaSet.Add("http://www.tempuri.org", "customer.xsd");
        schemaSet.Compile();

        // Retrieve the compiled XmlSchema object from the XmlSchemaSet 
        // by iterating over the Schemas property.
        XmlSchema customerSchema = null;
        foreach (XmlSchema schema in schemaSet.Schemas())
        {
            customerSchema = schema;
        }

        // Iterate over each XmlSchemaElement in the Values collection 
        // of the Elements property. 
        foreach (XmlSchemaElement element in customerSchema.Elements.Values)
        {

            Console.WriteLine("Element: {0}", element.Name);

            // Get the complex type of the Customer element.
            XmlSchemaComplexType complexType = element.ElementSchemaType as XmlSchemaComplexType;

            // If the complex type has any attributes, get an enumerator  
            // and write each attribute name to the console. 
            if (complexType.AttributeUses.Count > 0)
            {
                IDictionaryEnumerator enumerator =
                    complexType.AttributeUses.GetEnumerator();

                while (enumerator.MoveNext())
                {
                    XmlSchemaAttribute attribute =
                        (XmlSchemaAttribute)enumerator.Value;

                    Console.WriteLine("Attribute: {0}", attribute.Name);
                }
            }

            // Get the sequence particle of the complex type.
            XmlSchemaSequence sequence = complexType.ContentTypeParticle as XmlSchemaSequence;

            // Iterate over each XmlSchemaElement in the Items collection. 
            foreach (XmlSchemaElement childElement in sequence.Items)
            {
                Console.WriteLine("Element: {0}", childElement.Name);
            }
        }
    }

    static void ValidationCallback(object sender, ValidationEventArgs args)
    {
        if (args.Severity == XmlSeverityType.Warning)
            Console.Write("WARNING: ");
        else if (args.Severity == XmlSeverityType.Error)
            Console.Write("ERROR: ");

        Console.WriteLine(args.Message);
    }
}

XML-схема:

<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="network" type="netType"/>
    <xs:complexType name="netType">
        <xs:sequence>
            <xs:element name="Version">
                <xs:complexType>
                    <xs:sequence>
                        <xs:element name="Min" type="xs:int"/>
                        <xs:element name="Max" type="xs:int"/>
                    </xs:sequence>
                </xs:complexType>
            </xs:element>
            <xs:element name="File">
                <xs:complexType>
                    <xs:sequence>
                        <xs:element name="Min" type="xs:int"/>
                        <xs:element name="Max" type="xs:int"/>
                    </xs:sequence>
                </xs:complexType>
            </xs:element>
            <xs:element name="NW">
                <xs:complexType>
                    <xs:sequence>
                        <xs:element name="Ethernet">
                            <xs:complexType>
                                <xs:sequence>
                                    <xs:element name="Cons">
                                        <xs:simpleType>
                                            <xs:list itemType="xs:int"/>
                                        </xs:simpleType>
                                    </xs:element>
                                </xs:sequence>
                            </xs:complexType>
                        </xs:element>
                        <xs:element name="Mail"/>
                    </xs:sequence>
                </xs:complexType>
            </xs:element>
        </xs:sequence>
    </xs:complexType>
</xs:schema>

Программа работает без ошибок, но я получаю только элементы в первом дереве. Пример:

Вывод:

Element: Version
Element: File

Но мне нужны все элементы: Min, Max from Version и Min, Max from File:

Что мне нужно:

Element: Version
Element: Min
Element: Max
Element: File
Element: Min
Element: Max

Итак, мои вопросы:

  • Как я могу получить все элементы?
  • И могу ли я использовать элементы в своей программе, например: Version.Min = 5.4
Теги:
xml-parsing
xsd

1 ответ

1

Пожалуйста, найдите код ниже

static void Main(string[] args)
    {
        XmlSchemaSet schemaSet = new XmlSchemaSet();
        schemaSet.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
        schemaSet.Add("http://tempuri.org/customer.xsd", "customer.xsd");
        schemaSet.Compile();

        XmlSchema xmlSchema = null;
        foreach (XmlSchema schema in schemaSet.Schemas())
        {
            xmlSchema = schema;
        }
// Following 2 lines can be removed, as there is no use and may cause errors
   //         DataSet myDS = new DataSet();
     //       myDS.ReadXmlSchema("customer.xsd");

        foreach (object item in xmlSchema.Items)
        {
            XmlSchemaElement schemaElement = item as XmlSchemaElement;
            XmlSchemaComplexType complexType = item as XmlSchemaComplexType;

            if (schemaElement != null)
            {
                Console.Out.WriteLine("Schema Element: {0}", schemaElement.Name);

                XmlSchemaType schemaType = schemaElement.SchemaType;
                XmlSchemaComplexType schemaComplexType = schemaType as XmlSchemaComplexType;

                if (schemaComplexType != null)
                {
                    XmlSchemaParticle particle = schemaComplexType.Particle;
                    XmlSchemaSequence sequence = particle as XmlSchemaSequence;

                    if (sequence != null)
                    {
                        foreach (XmlSchemaElement childElement in sequence.Items)
                        {
                            Console.Out.WriteLine("    Element/Type: {0}:{1}", childElement.Name,
                                                  childElement.SchemaTypeName.Name);
                        }

                    }
                    if (schemaComplexType.AttributeUses.Count > 0)
                    {
                        IDictionaryEnumerator enumerator = schemaComplexType.AttributeUses.GetEnumerator();

                        while (enumerator.MoveNext())
                        {
                            XmlSchemaAttribute attribute = (XmlSchemaAttribute)enumerator.Value;

                            Console.Out.WriteLine("      Attribute/Type: {0}", attribute.Name);
                        }
                    }
                }
            }
            else if (complexType != null)
            {
                Console.Out.WriteLine("Complex Type: {0}", complexType.Name);
                OutputElements(complexType.Particle);
                if (complexType.AttributeUses.Count > 0)
                {
                    IDictionaryEnumerator enumerator = complexType.AttributeUses.GetEnumerator();

                    while (enumerator.MoveNext())
                    {
                        XmlSchemaAttribute attribute = (XmlSchemaAttribute)enumerator.Value;
                        Console.Out.WriteLine("      Attribute/Type: {0}", attribute.Name);
                    }
                }
            }
            Console.Out.WriteLine();
        }

        Console.Out.WriteLine();
        Console.In.ReadLine();
    }

    private static void OutputElements(XmlSchemaParticle particle)
    {
        XmlSchemaSequence sequence = particle as XmlSchemaSequence;
        XmlSchemaChoice choice = particle as XmlSchemaChoice;
        XmlSchemaAll all = particle as XmlSchemaAll;

        if (sequence != null)
        {
            Console.Out.WriteLine("  Sequence");

            for (int i = 0; i < sequence.Items.Count; i++)
            {
                XmlSchemaElement childElement = sequence.Items[i] as XmlSchemaElement;
                XmlSchemaSequence innerSequence = sequence.Items[i] as XmlSchemaSequence;
                XmlSchemaChoice innerChoice = sequence.Items[i] as XmlSchemaChoice;
                XmlSchemaAll innerAll = sequence.Items[i] as XmlSchemaAll;

                if (childElement != null)
                {
                    Console.Out.WriteLine("    Element/Type: {0}:{1}", childElement.Name,
                                          childElement.SchemaTypeName.Name);
                }
                else OutputElements(sequence.Items[i] as XmlSchemaParticle);
            }
        }
        else if (choice != null)
        {
            Console.Out.WriteLine("  Choice");
            for (int i = 0; i < choice.Items.Count; i++)
            {
                XmlSchemaElement childElement = choice.Items[i] as XmlSchemaElement;
                XmlSchemaSequence innerSequence = choice.Items[i] as XmlSchemaSequence;
                XmlSchemaChoice innerChoice = choice.Items[i] as XmlSchemaChoice;
                XmlSchemaAll innerAll = choice.Items[i] as XmlSchemaAll;

                if (childElement != null)
                {
                    Console.Out.WriteLine("    Element/Type: {0}:{1}", childElement.Name,
                                          childElement.SchemaTypeName.Name);
                }
                else OutputElements(choice.Items[i] as XmlSchemaParticle);
            }

            Console.Out.WriteLine();
        }
        else if (all != null)
        {
            Console.Out.WriteLine("  All");
            for (int i = 0; i < all.Items.Count; i++)
            {
                XmlSchemaElement childElement = all.Items[i] as XmlSchemaElement;
                XmlSchemaSequence innerSequence = all.Items[i] as XmlSchemaSequence;
                XmlSchemaChoice innerChoice = all.Items[i] as XmlSchemaChoice;
                XmlSchemaAll innerAll = all.Items[i] as XmlSchemaAll;

                if (childElement != null)
                {
                    Console.Out.WriteLine("    Element/Type: {0}:{1}", childElement.Name,
                                          childElement.SchemaTypeName.Name);
                }
                else OutputElements(all.Items[i] as XmlSchemaParticle);
            }
            Console.Out.WriteLine();
        }

    }

    static void ValidationCallback(object sender, ValidationEventArgs args)
    {
        if (args.Severity == XmlSeverityType.Warning)
            Console.Write("WARNING: ");
        else if (args.Severity == XmlSeverityType.Error)
            Console.Write("ERROR: ");

        Console.WriteLine(args.Message);
    }

И xsd, который я использовал:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="customer"
targetNamespace="http://tempuri.org/customer.xsd"
elementFormDefault="qualified"
xmlns="http://tempuri.org/customer.xsd"
xmlns:mstns="http://tempuri.org/customer.xsd"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
>
   <xs:element name="Version">
    <xs:complexType>
      <xs:sequence>
    <xs:element name="Min" type="xs:int"/>
    <xs:element name="Max" type="xs:int"/>
  </xs:sequence>
</xs:complexType>
  </xs:element>
  <xs:element name="File">
    <xs:complexType>
      <xs:sequence>
    <xs:element name="Min" type="xs:int"/>
    <xs:element name="Max" type="xs:int"/>
  </xs:sequence>
</xs:complexType>
  </xs:element>
</xs:schema>
  • 0
    Ваш код работает нормально, но не с моей полной схемой. Я получаю эту ошибку: DataSet не поддерживает 'union' или 'list' как simpleType. Я отредактирую свой вопрос со всей xsd
  • 0
    @ Stampy Эй, ты решил эту проблему?
Показать ещё 4 комментария

Ещё вопросы

Сообщество Overcoder
Наверх
Меню