Проблема десериализации CityGML - PullRequest
0 голосов
/ 22 февраля 2011

В настоящее время я работаю над сериализатором CityGML (мне нужны классы C # для определенных соответствующих объектов), и у меня возникли некоторые проблемы с корневой класс, который мне нужен для экземпляра System.Xml.Serialization.XmlSerializer. Я не знаю, насколько все здесь знакомы с CityGML, но вот описание ситуации. Я также описал, как я создал свои классы, если вы хотите пропустить это, вы можете начать читать от отметки / / *:

CityGML состоит из нескольких файлов .xsd, каждый из которых является модулем, описывающим определенный тип элементов (creation.xsd, transports.xsd, building.xsd, vegetation.xsd и т. д.), также имеющий корневой файл, CityGML.xsd. Как и следовало ожидать, каждый из модулей требует элементов из этот корневой файл. Также существует тот факт, что CityGML действительно наследует многое от GML, поэтому также необходим импорт из файлов .xsd GML.

Пока что с точки зрения генерации классов C # я пробовал два подхода, оба с использованием классического xsd.exe: - создание одного файла .cs, который будет включать все необходимые мне классы CityGML - единую командную строку:

xsd gml/feature.xsd gml/xlinks.xsd gml/geometryBasic2d.xsd gml/geometryComplexes.xsd gml/geometryPrimitives.xsd gml/smil20.xsd
    gml/smil20-language.xsd citygml/xAL.xsd citygml/appearance.xsd citygml/building.xsd citygml/cityFurniture.xsd citygml/cityObjectGroup.xsd
    citygml/generics.xsd citygml/landUse.xsd citygml/relief.xsd citygml/texturedSurface.xsd citygml/transportation.xsd citygml/vegetation.xsd
    citygml/waterBody.xsd citygml/CityGML.xsd citygml/cityGMLBase.xsd /classes /fields /namespace:CityGML

- the creation of a .cs file for each of the CityGML modules - one command line for each module:

xsd citygml/xAL.xsd /classes /namespace:xAL /o:out

xsd gml/feature.xsd citygml/xAL.xsd gml/geometryAggregates.xsd gml/xlinks.xsd
citygml/cityGMLBase.xsd /classes /namespace:CityGMLBase /o:out

xsd gml/feature.xsd citygml/cityGMLBase.xsd citygml/xAL.xsd gml/geometryAggregates.xsd
gml/xlinks.xsd citygml/appearance.xsd /classes /namespace:CityGMLAppearance /o:out

xsd gml/feature.xsd citygml/cityGMLBase.xsd citygml/xAL.xsd gml/geometryAggregates.xsd gml/xlinks.xsd citygml/building.xsd /classes /namespace:CityGMLBuilding /o:out

xsd gml/feature.xsd citygml/cityGMLBase.xsd citygml/xAL.xsd gml/geometryAggregates.xsd gml/xlinks.xsd citygml/cityFurniture.xsd /classes /namespace:CityGMLCityFurniture /o:out

xsd citygml/cityGMLBase.xsd gml/feature.xsd gml/xlinks.xsd citygml/xAL.xsd gml/geometryAggregates.xsd citygml/cityObjectGroup.xsd /classes /namespace:CityGMLCityObjectGroup /o:out

xsd gml/feature.xsd citygml/cityGMLBase.xsd citygml/xAL.xsd gml/geometryAggregates.xsd gml/xlinks.xsd citygml/generics.xsd /classes /namespace:CityGMLGenerics /o:out

xsd gml/feature.xsd citygml/cityGMLBase.xsd citygml/xAL.xsd gml/geometryAggregates.xsd gml/xlinks.xsd citygml/landUse.xsd /classes /namespace:CityGMLLandUse /o:out

xsd citygml/cityGMLBase.xsd citygml/xAL.xsd gml/xlinks.xsd citygml/cityFurniture.xsd gml/coverage.xsd citygml/relief.xsd /classes /namespace:CityGMLRelief /o:out

xsd gml/feature.xsd citygml/cityGMLBase.xsd citygml/xAL.xsd gml/geometryAggregates.xsd gml/xlinks.xsd citygml/texturedSurface.xsd /classes /namespace:CityGMLTexturedSurface /o:out

xsd gml/feature.xsd citygml/cityGMLBase.xsd citygml/xAL.xsd gml/geometryComplexes.xsd gml/xlinks.xsd citygml/transportation.xsd /classes /namespace:CityGMLTransportation /o:out

xsd gml/feature.xsd citygml/cityGMLBase.xsd citygml/xAL.xsd gml/geometryAggregates.xsd 
gml/xlinks.xsd citygml/vegetation.xsd /classes /namespace:CityGMLVegetation /o:out

xsd gml/feature.xsd citygml/cityGMLBase.xsd citygml/xAL.xsd gml/geometryAggregates.xsd gml/xlinks.xsd citygml/waterBody.xsd /classes /namespace:CityGMLWaterBody /o:out

Для каждой из команд последний .xsd является желаемым модулем, в то время как остальные являются необходимыми для импорта.

К сожалению, хотя xsd.exe имеет дело с импортом из других файлов .xsd и создает классы необходимого файла, а также из импортированных файлы, это делает это "напрямую", складывая все эти классы в один файл .cs. Видимо нет возможности разделить нужные классы из импортированных классов в разных файлах .cs. Следовательно, мой первый вопрос - это ЛЮБЫЕ (DE) ИНСТРУМЕНТЫ СЕРИАЛИЗАЦИИ, ПОХОЖИЕ НА XSD.EXE, КОТОРЫЕ РАБОТАЮТ С ИМПОРТИРОВАННЫМИ .XSD-ФАЙЛАМИ И СОЗДАТЬ НЕОБХОДИМОСТЬ .CS ФАЙЛ ИЕРАРХИЯ? Это позволит избежать повторения, например, классов feature.xsd во всем вышеприведенном модуле. .cs файлы.

/ / ** * 1016

Продолжая, проблема, которая на самом деле вызывает у меня проблемы, связана с экземпляром XmlSerializer, который не может быть создан, поскольку базовый CityGML Тип объекта CityModelType, который также является корневым классом во всей иерархии, недопустим:

System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(typeof(CityModelType));

Это назначение сначала дало ошибку, касающуюся использования XmlTextAttribute для определения строки [], которая отображала «отражение» CityModelType невозможно. Я заменил XmlTextAttribute на XmlAttributeAttribute и текущие сообщения, происхождение которых я не смог отследить, это (да, я работаю по-французски):

System.InvalidOperationException: Impossible de générer une classe temporaire (result=1).
error CS0030: Impossible de convertir le type 'CityGML.LineStringSegmentType[]' en 'CityGML.LineStringSegmentType'
error CS0030: Impossible de convertir le type 'CityGML.LineStringSegmentType[]' en 'CityGML.LineStringSegmentType'
error CS0030: Impossible de convertir le type 'CityGML.LineStringSegmentType[]' en 'CityGML.LineStringSegmentType'
error CS0029: Impossible de convertir implicitement le type 'CityGML.LineStringSegmentType' en 'CityGML.LineStringSegmentType[]'
error CS0029: Impossible de convertir implicitement le type 'CityGML.LineStringSegmentType' en 'CityGML.LineStringSegmentType[]'
error CS0029: Impossible de convertir implicitement le type 'CityGML.LineStringSegmentType' en 'CityGML.LineStringSegmentType[]'

Прежде всего, единственные вхождения LineStringSegmentType связаны с кривыми, которые я не использую в своем файле .gml. Они определены так:

    public partial class LineStringSegmentType : AbstractCurveSegmentType {

        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute("coordinates", typeof(CoordinatesType))]
        [System.Xml.Serialization.XmlElementAttribute("pointProperty", typeof(PointPropertyType))]
        [System.Xml.Serialization.XmlElementAttribute("pointRep", typeof(PointPropertyType))]
        [System.Xml.Serialization.XmlElementAttribute("pos", typeof(DirectPositionType))]
        [System.Xml.Serialization.XmlElementAttribute("posList", typeof(DirectPositionListType))]
        [System.Xml.Serialization.XmlChoiceIdentifierAttribute("ItemsElementName")]
        public object[] Items;

        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute("ItemsElementName")]
        [System.Xml.Serialization.XmlIgnoreAttribute()]
        public ItemsChoiceType2[] ItemsElementName;

        /// <remarks/>
        [System.Xml.Serialization.XmlAttributeAttribute()]
        public CurveInterpolationType interpolation;

        /// <remarks/>
        [System.Xml.Serialization.XmlIgnoreAttribute()]
        public bool interpolationSpecified;

        public LineStringSegmentType() {
            this.interpolation = CurveInterpolationType.linear;
        }
    }

... и они здесь используются:

public partial class TinType : TriangulatedSurfaceType {

    /// <remarks/>
    [System.Xml.Serialization.XmlArrayItemAttribute("LineStringSegment", typeof(LineStringSegmentType), IsNullable=false)]
    public LineStringSegmentType[][] stopLines;

    /// <remarks/>
    [System.Xml.Serialization.XmlArrayItemAttribute("LineStringSegment", typeof(LineStringSegmentType), IsNullable=false)]
    public LineStringSegmentType[][] breakLines;

    /// <remarks/>
    public LengthType maxLength;

    /// <remarks/>
    public TinTypeControlPoint controlPoint;
}

... из этого фрагмента gml: geometryPrimitives.xsd:

<complexType name="TinType">
    [...]
    <complexContent>
        <extension base="gml:TriangulatedSurfaceType">
            <sequence>
                <element name="stopLines" type="gml:LineStringSegmentArrayPropertyType" minOccurs="0" maxOccurs="unbounded">
                    [...]
                </element>
                <element name="breakLines" type="gml:LineStringSegmentArrayPropertyType" minOccurs="0" maxOccurs="unbounded">
                    [...]
                </element>
                <element name="maxLength" type="gml:LengthType">
                    [...]
                </element>
                <element name="controlPoint">
                    [...]
                    <complexType>
                        <choice>
                            <element ref="gml:posList"/>
                            <group ref="gml:geometricPositionGroup" minOccurs="3" maxOccurs="unbounded"/>
                        </choice>
                    </complexType>
                </element>
            </sequence>
        </extension>
    </complexContent>
</complexType>

<complexType name="LineStringSegmentArrayPropertyType">
    <sequence>
        <element ref="gml:LineStringSegment" minOccurs="0" maxOccurs="unbounded"/>
    </sequence>
</complexType>

Я не вижу, в чем проблема, и это довольно странно. Надеемся услышать от вас скоро. Спасибо.

Ура, Victor

1 Ответ

1 голос
/ 22 февраля 2011

"ЛЮБЫЕ (DE) ЛИБО ИНСТРУМЕНТЫ СЕРИАЛИЗАЦИИ, ПОХОЖИЕ НА XSD.EXE, КОТОРЫЕ РАБОТАЮТ С ИМПОРТИРОВАННЫМИ .XSD-ФАЙЛАМИ И СОЗДАЮТ НЕОБХОДИМОСТЬ. ИСКУССТВО ФАЙЛА ФАЙЛА?"Я использую Xsd2Code , что было отправлено богом после того, как у меня возникли похожие проблемы iwht xsd.exe

...