Проблема десериализации CityGML
В настоящее время я работаю над сериализатором CityGML (de) - мне нужны классы C# для определенных соответствующих объектов - и у меня возникли некоторые проблемы с корневым классом, который мне нужен для экземпляра System.Xml.Serialization.XmlSerializer. Я не знаю, насколько все здесь знакомы с CityGML, но вот описание ситуации. Я также описал, как я создавал свои классы, если вы хотите пропустить это, вы можете начать читать со знака // *:
CityGML состоит из нескольких файлов.xsd, каждый из которых представляет собой модуль, описывающий элементы определенного типа (Appearance.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.
// *
Далее, проблема, которая на самом деле вызывает у меня проблемы, связана с экземпляром 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>
Я не вижу, где проблема, и это довольно странно. Надеемся услышать от вас скоро. Благодарю.
Ура, Виктор
1 ответ
"ЛЮБЫЕ (DE) ЛИБО ИНСТРУМЕНТЫ СЕРИАЛИЗАЦИИ, ПОХОЖИЕ НА XSD.EXE, КОТОРЫЕ РАБОТАЮТ С ИМПОРТИРОВАННЫМИ.XSD-ФАЙЛАМИ И СОЗДАЮТ НЕКОТОРЫЕ. ИССЛЕДОВАНИЯ ФАЙЛОВ CS?"
Да, действительно, я использую Xsd2Code, который был богом послать после того, как у меня были подобные проблемы iwht xsd.exe