首页 > 解决方案 > 如何在 asp.net 中将所有 xsd 元素显示为列表

问题描述

我目前正在做一些事情,我必须将所有 xsd 嵌套元素显示为 asp.net 中的内容列表,我当前的代码是

    XmlSchema schema = new XmlSchema();        
    schema = XmlSchema.Read(new XmlTextReader("example.xsd", null);

    XmlSchemaSet schemaSet = new XmlSchemaSet();        
    schemaSet.Add(schema);
    schemaSet.Compile();


    XmlSchema workingSchema = null;
    foreach (XmlSchema sc in schemaSet.Schemas())
    {
        workingSchema = sc;
    }


    DropDownList1.Items.Clear();


    ///cycle through elements, adding to dropdownlist

    foreach (XmlSchemaElement element in workingSchema.Elements.Values)
    {
        DropDownList1.Items.Add(element.Name);


        // Get the complex type of the element.

        XmlSchemaComplexType complexType = element.ElementSchemaType as XmlSchemaComplexType;
        if (complexType!=null)
        {
            XmlSchemaSequence seq = (XmlSchemaSequence)complexType.ContentTypeParticle;
            foreach (XmlSchemaElement element2 in seq.Items)
            {
                DropDownList1.Items.Add(element2.Name);
            }


        }


    }

这是我使用的xsd文件

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
           xmlns:tns="http://tempuri.org/PurchaseOrderSchema.xsd"
           targetNamespace="http://tempuri.org/PurchaseOrderSchema.xsd"
           elementFormDefault="qualified">
 <xsd:element name="PurchaseOrder" type="tns:PurchaseOrderType"/>
 <xsd:complexType name="PurchaseOrderType">
  <xsd:sequence>
   <xsd:element name="ShipTo" type="tns:USAddress" maxOccurs="2"/>
   <xsd:element name="BillTo" type="tns:USAddress"/>
  </xsd:sequence>
  <xsd:attribute name="OrderDate" type="xsd:date"/>
 </xsd:complexType>

 <xsd:complexType name="USAddress">
  <xsd:sequence>
   <xsd:element name="name"   type="xsd:string"/>
   <xsd:element name="street" type="xsd:string"/>
   <xsd:element name="city"   type="xsd:string"/>
   <xsd:element name="state"  type="xsd:string"/>
   <xsd:element name="zip"    type="xsd:integer"/>
  </xsd:sequence>
  <xsd:attribute name="country" type="xsd:NMTOKEN" fixed="US"/>
 </xsd:complexType>
</xsd:schema>

在这里它只显示采购订单、运送到、账单到但我需要显示所有内容,包括名称、街道、城市等。如何做到这一点

标签: c#asp.netxmlxsd

解决方案


不确定这真的有多大帮助。仅仅拥有没有父母的元素并不是很有用。我使用 Xml Linq 来获得结果

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

namespace ConsoleApplication161
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            List<string> names = doc.Descendants().Where(x => x.Name.LocalName == "element").Select(x => (string)x.Attribute("name")).ToList();



        }
    }
}

推荐阅读