2012-08-15 2 views
3

는 그 같은 XSD 파일이 있습니다중첩 요소 (complexType 및 simpleType 요소 및 특성)가있는 xsd 파일을 구문 분석하는 방법은 무엇입니까?

<?xml version="1.0" encoding="utf-8" ?> 
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema"> 
    <xs:element name="transfer"> 
     <xs:complexType> 
      <xs:sequence> 
       <xs:element name="sourceGLN" type="xs:string" minOccurs="1" maxOccurs="1" /> 
       <xs:element name="destinationGLN" type="xs:string" minOccurs="1" maxOccurs="1" /> 
       <xs:element name="actionType" minOccurs="1" maxOccurs="1"> 
        <xs:simpleType> 
         <xs:restriction base="xs:string"> 
          <xs:enumeration value="P" /> <!-- Mal Alim (Purchase) --> 
          <xs:enumeration value="S" /> <!-- Satis (Sale) --> 
          <xs:enumeration value="C" /> <!-- Cancel Sale (Cancel) --> 
          <xs:enumeration value="R" /> <!-- Iade (Return) --> 
          <xs:enumeration value="D" /> <!-- Deaktivasyon (Deactivation) --> 
          <xs:enumeration value="M" /> <!-- Uretim (Manufacture) --> 
          <xs:enumeration value="I" /> <!-- Ithalat (Import) --> 
          <xs:enumeration value="X" /> <!-- Ihrac (eXport) --> 
          <xs:enumeration value="O" /> <!-- Sarf (cOnsume) --> 
          <xs:enumeration value="N" /> <!-- Bilgi (iNformation) --> 
          <xs:enumeration value="T" /> <!-- Devir (Transfer) --> 
          <xs:enumeration value="L" /> <!-- Devir Iptal (canceL Transfer) --> 
          <xs:enumeration value="F" /> <!-- Aktarim (non-its transFer) --> 
          <xs:enumeration value="K" /> <!-- Aktarim Iptal (non-its cancel transfer) --> 
         </xs:restriction> 
        </xs:simpleType> 
       </xs:element> 
       <xs:element name="shipTo" type="xs:string" minOccurs="0" maxOccurs="1" /> 
       <xs:element name="documentNumber" type="xs:string" minOccurs="0" maxOccurs="1" /> 
       <xs:element name="documentDate" type="xs:date" minOccurs="0" maxOccurs="1" /> 
       <xs:element name="note" type="xs:string" minOccurs="0" maxOccurs="1" /> 
       <xs:element name="version" type="xs:string" minOccurs="0" maxOccurs="1" /> 
       <xs:element name="carrier" type="carrierType" minOccurs="1" maxOccurs="unbounded" /> 
      </xs:sequence> 
     </xs:complexType> 
    </xs:element> 
    <xs:complexType name="carrierType"> 
     <xs:sequence minOccurs="1" maxOccurs="unbounded"> 
      <xs:choice minOccurs="1" maxOccurs="1"> 
       <xs:element name="productList" type="productListType" minOccurs="1" maxOccurs="1" /> 
       <xs:element name="carrier" type="carrierType" minOccurs="1" maxOccurs="1" /> 
      </xs:choice> 
     </xs:sequence> 
     <xs:attribute name="carrierLabel" use="required"> 
      <xs:simpleType> 
       <xs:restriction base="xs:string"> 
        <xs:length value="20" /> 
       </xs:restriction> 
      </xs:simpleType> 
     </xs:attribute> 
     <xs:attribute name="containerType" type="xs:string" use="optional" /> 
    </xs:complexType> 
    <xs:complexType name="productListType"> 
     <xs:sequence> 
      <xs:element name="serialNumber" type="xs:string" minOccurs="1" maxOccurs="unbounded" /> 
     </xs:sequence> 
     <xs:attribute name="GTIN" type="xs:string" use="required" /> 
     <xs:attribute name="lotNumber" type="xs:string" use="required" /> 
     <xs:attribute name="productionDate" type="xs:date" use="optional" /> 
     <xs:attribute name="expirationDate" type="xs:date" use="required" /> 
     <xs:attribute name="PONumber" type="xs:string" use="optional" /> 
    </xs:complexType> 
</xs:schema> 

을 그리고 그 같은 코드를 가지고 : 나는 그것이 나에게 단지 첫 번째 요소 '요소의 이름을 제공 실행하려고

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

namespace ConsoleApplication1 
{ 
    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.w3.org/2001/XMLSchema", "C:\\Users\\ahmet.ulusoy\\Desktop\\pts_xml_schema_v_1_4.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); 
     } 
    } 
} 

. 그런 다음 어떻게 다른 2 개의 x를 사용할 수 있습니까? complexType name = "carrierType"및 xs : complexType name = "productListType"및 하위 요소 및 특성?

이 부분을 작성하여 코드를 업데이트 할 예정입니다.

또한이 데이터 및 데이터 유형을 사용하여 일반 클래스를 만들고 싶습니다. 나는 무엇을해야합니까?

미리 감사드립니다. (당신이 xs:complexType name="carrierType" and xs:complexType name="productListType" 찾고으로, 또는 이름) 컴파일 된 XmlSchemaSet를 들어

답변

3

위와 같은 xsd 문서가있는 경우 이와 같은 코드가 필요할 수 있습니다.

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Xml.Schema; 
using System.Collections; 
using System.Data; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     private static void Main(string[] args) 
     { 
      XmlSchemaSet schemaSet = new XmlSchemaSet(); 
      schemaSet.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); 
      schemaSet.Add("http://www.w3.org/2001/XMLSchema", "C:\\Users\\ahmet.ulusoy\\Desktop\\pts_xml_schema_v_1_4.xsd"); 
      schemaSet.Compile(); 

      XmlSchema xmlSchema = null; 
      foreach (XmlSchema schema in schemaSet.Schemas()) 
      { 
       xmlSchema = schema; 
      } 

      DataSet myDS = new DataSet(); 
      myDS.ReadXmlSchema("C:\\Users\\ahmet.ulusoy\\Desktop\\pts_xml_schema_v_1_4.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); 
     } 
    } 

} 

그리고 더욱 구체적인 경우에이를 향상시킬 수 있습니다. 예를 들면 attributegroup, group, vs ... 또한 이제는 해당 xsd에 대한 일반 클래스가 있습니다. 이제 위의 xsd에서 참조하는 xml로 일반 클래스 (이전에 만들어진)를 설정합니다.

이러한 작업을 통해 프로젝트의 노드별로 XML 노드를 읽는 메카니즘을 취소합니다.

1

, 나는 글로벌 콘텐츠를 이동하려면 다음 컬렉션을 사용합니다 :

속성 그룹, 그룹, 표기법과 같은 다른 모든 경우에는 각 스키마 (요소에 대한 방식)로 이동해야합니다.

또한 PSVI 속성을 사용하고 있습니다. 그냥 다른 사람이 읽을 수 있도록 "소스"XSD와 다릅니다. 예를 들어 AttributeUses은 다른 요구 사항에 따라 차이가있을 수있는 방식으로 Attributes과 다릅니다.

+0

도움 주셔서 감사합니다. – historyoftheviolence

관련 문제