热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

xsd.exe使用数组中的多个元素生成c#-xsd.exegeneratedc#withmultipleelementsinanarray

IhaveasetofXMLschemafilesprovidedtome.IcannotchangedtheXMLasthesewillbeupdatedo

I have a set of XML schema files provided to me. I cannot changed the XML as these will be updated on occasion. I am using xsd.exe to convert the schema files to generated c# code. I cannot use any third party tools. Part of one of the XML schema files appears as such:

我有一组XML模式文件提供给我。我无法更改XML,因为这些有时会更新。我正在使用xsd.exe将架构文件转换为生成的c#代码。我不能使用任何第三方工具。其中一个XML模式文件的一部分显示如下:


  
    
    
      
      
      
      
    
  

When converted to c#, I get a result such as this:

当转换为c#时,我得到如下结果:

[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://abcxyz.com")]
public partial class LocationType
{

    private object[] itemsField;

    private ItemsChoiceType[] itemsElementNameField;

    /// 
    [System.Xml.Serialization.XmlElementAttribute("Address", typeof(string), Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
    [System.Xml.Serialization.XmlElementAttribute("City", typeof(string), Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
    [System.Xml.Serialization.XmlElementAttribute("LocNum", typeof(string), Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
    [System.Xml.Serialization.XmlElementAttribute("Longitude", typeof(decimal), Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
    [System.Xml.Serialization.XmlElementAttribute("State", typeof(LocationTypeState), Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
    [System.Xml.Serialization.XmlChoiceIdentifierAttribute("ItemsElementName")]
    public object[] Items
    {
        get { return this.itemsField; }
        set { this.itemsField = value; }
    }

    /// 
    [System.Xml.Serialization.XmlElementAttribute("ItemsElementName")]
    [System.Xml.Serialization.XmlIgnoreAttribute()]
    public ItemsChoiceType[] ItemsElementName
    {
        get { return this.itemsElementNameField; }
        set { this.itemsElementNameField = value; }
    }
}

Since these all get generated to partial classes, I am free to add additional code. I need to be able to read/set the individual properties, such as Name, Address, City, etc.

由于这些都生成了部分类,我可以自由添加其他代码。我需要能够读取/设置各个属性,例如姓名,地址,城市等。

I need to be able to serialize these objects to match the schema.

我需要能够序列化这些对象以匹配架构。

Is there a way in c# to create a public property that will read or set the value in the Items array at the proper sequence, etc.? ie:

在c#中有没有办法创建一个公共属性,以适当的顺序读取或设置Items数组中的值,等等?即:

public partial class LocationType
{
    public string Address
    {
        get
        {
            // code here to return the correct Items[] element
        }
        set
        {
            // code here to set the correct Items[] element
        }
    }
}

2 个解决方案

#1


4  

What that schema says is that if some outer type contains an element of type LocationType, one would expect to find inside either

该模式所说的是,如果某个外部类型包含一个类型为LocationType的元素,那么人们可能希望在其中找到

1) A sub-element , OR

1)子元素 ,OR

2) These sub-elements in sequence: ,

, and .

2)这些子元素依次为:

Thus the data here is polymorphic, even though it isn't being explicitly modeled as such in the c# classes generated by xsd.exe. This sort of makes sense -- a location might be specified explicitly, or indirectly as a look-up in a table.

因此,这里的数据是多态的,即使它没有在xsd.exe生成的c#类中明确建模。这种情况很有意义 - 可以明确指定位置,也可以间接指定为表中的查找。

When deserializing a polymorphic sequence like this, XmlSerializer puts each element it finds in the array field corresponding to the elements in the sequence, in this case the array Items. In addition, there should be another corresponding array field identified by the XmlChoiceIdentifierAttribute attribute, in this case ItemsElementName. The entries in this array must needs be in 1-1 correspondence with the Items array. It records the name of the element that was deserialized in each index of the Items array, by way of the ItemsChoiceType enumeration, whose enum names must match the names in the XmlElementAttribute attributes decorating the Items array. This allows the specific choice of polymorphic data to be known.

当像这样反序列化多态序列时,XmlSerializer将它找到的每个元素放在对应于序列中元素的数组字段中,在本例中是数组Items。此外,应该有另一个由XmlChoiceIdentifierAttribute属性标识的相应数组字段,在本例中为ItemsElementName。此数组中的条目必须与Items数组1-1对应。它通过ItemsChoiceType枚举记录Items数组的每个索引中反序列化的元素的名称,其枚举名称必须与装饰Items数组的XmlElementAttribute属性中的名称匹配。这允许已知多态数据的特定选择。

Thus, to round out the implementation of your LocationType class, you will need to determine whether a given LocationType is direct or indirect; fetch various properties out; and for each type (direct or indirect), set all required data.

因此,为了完善LocationType类的实现,您需要确定给定的LocationType是直接还是间接;获取各种属性;对于每种类型(直接或间接),设置所有必需的数据。

Here is a prototype of that. (You didn't include the definition for LocationTypeState in your question, so I'm just treating it as a string):

这是原型。 (你没有在你的问题中包含LocationTypeState的定义,所以我只是将它视为一个字符串):

public partial class LocationType
{
    public LocationType() { }

    public LocationType(string locNum)
    {
        SetIndirectLocation(locNum);
    }

    public LocationType(string name, string address, string city, string state)
    {
        SetDirectLocation(name, address, city, state);
    }

    public bool IsIndirectLocation
    {
        get
        {
            return Array.IndexOf(ItemsElementName, ItemsChoiceType.LocNum) >= 0;
        }
    }

    public string Address { get { return (string)XmlPolymorphicArrayHelper.GetItem(Items, ItemsElementName, ItemsChoiceType.Address); } }

    public string LocNum { get { return (string)XmlPolymorphicArrayHelper.GetItem(Items, ItemsElementName, ItemsChoiceType.LocNum); } }

    // Other properties as desired.

    public void SetIndirectLocation(string locNum)
    {
        if (string.IsNullOrEmpty(locNum))
            throw new ArgumentException();
        object[] newItems = new object[] { locNum };
        ItemsChoiceType [] newItemsElementName = new ItemsChoiceType [] { ItemsChoiceType.LocNum };
        this.Items = newItems;
        this.ItemsElementName = newItemsElementName;
    }

    public void SetDirectLocation(string name, string address, string city, string state)
    {
        // In the schema, "City" is mandatory, others are optional.
        if (string.IsNullOrEmpty(city))
            throw new ArgumentException();
        List newItems = new List();
        List newItemsElementName = new List();
        if (name != null)
        {
            newItems.Add(name);
            newItemsElementName.Add(ItemsChoiceType.Name);
        }
        if (address != null)
        {
            newItems.Add(address);
            newItemsElementName.Add(ItemsChoiceType.Address);
        }
        newItems.Add(city);
        newItemsElementName.Add(ItemsChoiceType.City);
        if (state != null)
        {
            newItems.Add(state);
            newItemsElementName.Add(ItemsChoiceType.State);
        }
        this.Items = newItems.ToArray();
        this.ItemsElementName = newItemsElementName.ToArray();
    }
}

public static class XmlPolymorphicArrayHelper
{
    public static TResult GetItem(TResult[] items, TIDentifier[] itemIdentifiers, TIDentifier itemIdentifier)
    {
        if (itemIdentifiers == null)
        {
            Debug.Assert(items == null);
            return default(TResult);
        }
        Debug.Assert(items.Length == itemIdentifiers.Length);
        var i = Array.IndexOf(itemIdentifiers, itemIdentifier);
        if (i <0)
            return default(TResult);
        return items[i];
    }
}

#2


3  

Here's the final solution we came up with that leverages when I learned from the original answer. This static class is used to get and set the appropriate properties.

这是我们从原始答案中学到的最终解决方案。此静态类用于获取和设置适当的属性。

public static class XmlPolymorphicArrayHelper
{
    public static TResult GetItem(TResult[] items, TIDentifier[] itemIdentifiers, TIDentifier itemIdentifier)
    {
        if (itemIdentifiers == null)
        {
            return default(TResult);
        }
        var i = Array.IndexOf(itemIdentifiers, itemIdentifier);
        return i <0 ? default(TResult) : items[i];
    }

    public static void SetItem(ref TResult[] items, ref TIDentifier[] itemIdentifiers, TIDentifier itemIdentifier, TResult value)
    {
        if (itemIdentifiers == null)
        {
            itemIdentifiers = new[] { itemIdentifier };
            items = new[] { value };

            return;
        }

        var i = Array.IndexOf(itemIdentifiers, itemIdentifier);
        if (i <0)
        {
            var newItemIdentifiers = itemIdentifiers.ToList();
            newItemIdentifiers.Add(itemIdentifier);
            itemIdentifiers = newItemIdentifiers.ToArray();

            var newItems = items.ToList();
            newItems.Add(value);
            items = newItems.ToArray();
        }
        else
        {
            items[i] = value;
        }

    }
}

And then call them from the partial class like this:

然后从部分类中调用它们,如下所示:

public partial class LocationType
{
    [XmlIgnore]
    public string Address
    {
        get
        {
            return (string)XmlPolymorphicArrayHelper.GetItem(Items, ItemsElementName, ItemsChoiceType.Address);
        }
        set
        {
            XmlPolymorphicArrayHelper.SetItem(ref this.itemsField, ref this.itemsElementNameField, ItemsChoiceType.Address, value);
        }
    }
}

This sets/creates the appropriate member on the Items array and I can use this for the multiple classes that implement this pattern.

这在Items数组上设置/创建了适当的成员,我可以将它用于实现此模式的多个类。


推荐阅读
  • android listview OnItemClickListener失效原因
    最近在做listview时发现OnItemClickListener失效的问题,经过查找发现是因为button的原因。不仅listitem中存在button会影响OnItemClickListener事件的失效,还会导致单击后listview每个item的背景改变,使得item中的所有有关焦点的事件都失效。本文给出了一个范例来说明这种情况,并提供了解决方法。 ... [详细]
  • Spring源码解密之默认标签的解析方式分析
    本文分析了Spring源码解密中默认标签的解析方式。通过对命名空间的判断,区分默认命名空间和自定义命名空间,并采用不同的解析方式。其中,bean标签的解析最为复杂和重要。 ... [详细]
  • CF:3D City Model(小思维)问题解析和代码实现
    本文通过解析CF:3D City Model问题,介绍了问题的背景和要求,并给出了相应的代码实现。该问题涉及到在一个矩形的网格上建造城市的情景,每个网格单元可以作为建筑的基础,建筑由多个立方体叠加而成。文章详细讲解了问题的解决思路,并给出了相应的代码实现供读者参考。 ... [详细]
  • 本文介绍了一个适用于PHP应用快速接入TRX和TRC20数字资产的开发包,该开发包支持使用自有Tron区块链节点的应用场景,也支持基于Tron官方公共API服务的轻量级部署场景。提供的功能包括生成地址、验证地址、查询余额、交易转账、查询最新区块和查询交易信息等。详细信息可参考tron-php的Github地址:https://github.com/Fenguoz/tron-php。 ... [详细]
  • Android实战——jsoup实现网络爬虫,糗事百科项目的起步
    本文介绍了Android实战中使用jsoup实现网络爬虫的方法,以糗事百科项目为例。对于初学者来说,数据源的缺乏是做项目的最大烦恼之一。本文讲述了如何使用网络爬虫获取数据,并以糗事百科作为练手项目。同时,提到了使用jsoup需要结合前端基础知识,以及如果学过JS的话可以更轻松地使用该框架。 ... [详细]
  • 使用nodejs爬取b站番剧数据,计算最佳追番推荐
    本文介绍了如何使用nodejs爬取b站番剧数据,并通过计算得出最佳追番推荐。通过调用相关接口获取番剧数据和评分数据,以及使用相应的算法进行计算。该方法可以帮助用户找到适合自己的番剧进行观看。 ... [详细]
  • YOLOv7基于自己的数据集从零构建模型完整训练、推理计算超详细教程
    本文介绍了关于人工智能、神经网络和深度学习的知识点,并提供了YOLOv7基于自己的数据集从零构建模型完整训练、推理计算的详细教程。文章还提到了郑州最低生活保障的话题。对于从事目标检测任务的人来说,YOLO是一个熟悉的模型。文章还提到了yolov4和yolov6的相关内容,以及选择模型的优化思路。 ... [详细]
  • 本文介绍了设计师伊振华受邀参与沈阳市智慧城市运行管理中心项目的整体设计,并以数字赋能和创新驱动高质量发展的理念,建设了集成、智慧、高效的一体化城市综合管理平台,促进了城市的数字化转型。该中心被称为当代城市的智能心脏,为沈阳市的智慧城市建设做出了重要贡献。 ... [详细]
  • Commit1ced2a7433ea8937a1b260ea65d708f32ca7c95eintroduceda+Clonetraitboundtom ... [详细]
  • 目录实现效果:实现环境实现方法一:基本思路主要代码JavaScript代码总结方法二主要代码总结方法三基本思路主要代码JavaScriptHTML总结实 ... [详细]
  • baresip android编译、运行教程1语音通话
    本文介绍了如何在安卓平台上编译和运行baresip android,包括下载相关的sdk和ndk,修改ndk路径和输出目录,以及创建一个c++的安卓工程并将目录考到cpp下。详细步骤可参考给出的链接和文档。 ... [详细]
  • Html5-Canvas实现简易的抽奖转盘效果
    本文介绍了如何使用Html5和Canvas标签来实现简易的抽奖转盘效果,同时使用了jQueryRotate.js旋转插件。文章中给出了主要的html和css代码,并展示了实现的基本效果。 ... [详细]
  • 网络请求模块选择——axios框架的基本使用和封装
    本文介绍了选择网络请求模块axios的原因,以及axios框架的基本使用和封装方法。包括发送并发请求的演示,全局配置的设置,创建axios实例的方法,拦截器的使用,以及如何封装和请求响应劫持等内容。 ... [详细]
  • React基础篇一 - JSX语法扩展与使用
    本文介绍了React基础篇一中的JSX语法扩展与使用。JSX是一种JavaScript的语法扩展,用于描述React中的用户界面。文章详细介绍了在JSX中使用表达式的方法,并给出了一个示例代码。最后,提到了JSX在编译后会被转化为普通的JavaScript对象。 ... [详细]
  • 本文整理了315道Python基础题目及答案,帮助读者检验学习成果。文章介绍了学习Python的途径、Python与其他编程语言的对比、解释型和编译型编程语言的简述、Python解释器的种类和特点、位和字节的关系、以及至少5个PEP8规范。对于想要检验自己学习成果的读者,这些题目将是一个不错的选择。请注意,答案在视频中,本文不提供答案。 ... [详细]
author-avatar
儒雅的aaaaaaaaaaa
这个家伙很懒,什么也没留下!
Tags | 热门标签
RankList | 热门文章
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有