Nano Hash - криптовалюты, майнинг, программирование

Xsd2Code — использование «любого» элемента для объединения схем

Я давний программист, но довольно новичок в C# и XML (к сожалению, одновременно). В рамках проекта, над которым я работаю, мне нужно создать XML-файлы, представляющие счета-фактуры в соответствии со стандартом GS1. Корневой файл xsd содержит следующий сегмент:

<xs:complexType name="StandardBusinessDocument">
    <xs:sequence>
        <xs:element ref="StandardBusinessDocumentHeader" minOccurs="0"/>
        <xs:any namespace="##other" processContents="lax"/>
    </xs:sequence>
</xs:complexType>

Счет-фактура определен в другом файле Invoice.xsd.

Я запустил Xsd2Code для обоих файлов xsd по отдельности и могу нормально заполнять сгенерированные объекты. Я также вижу, что объект StandardBusinessDocument имеет свойство StandardBusinessDocumentHeader и свойство Any. Но я не могу понять, как присвоить объект Invoice свойству Any. Если я пишу xStandardBusinessDocument.Any = new Invoice.InvoiceType();, я получаю сообщение об ошибке: Cannot implicity convert type 'EDISalesInvoices.BusinessObjects.Invoice.InvoiceType' to 'System.Xml.XmlElement'.

Конечно, в конце я хочу иметь возможность сериализовать и получить одну выходную строку XML.

Спасибо

Уэйн Айвори

public partial class InvoiceType : DocumentType
{

    private EntityIdentificationType invoiceIdentificationField;

    private ISO4217_CodeType invoiceCurrencyField;

    private InvoiceTypeCodeListType invoiceTypeField;

    private ISO3166_1CodeType countryOfSupplyOfGoodsField;

    private ShipToLogisticsType shipToField;

    private InvoicePartyType payerField;

    private InvoicePartyType payeeField;

    private InvoicePartyType remitToField;

    private InvoicePartyType taxRepresentativeField;

    private InvoicePartyType buyerField;

    private InvoicePartyType sellerField;

    private TimePeriodType invoicingPeriodField;

    private List<InvoiceLineItemType> invoiceLineItemField;

    private InvoiceTotalsType invoiceTotalsField;

    private List<InvoiceAllowanceChargeType> invoiceAllowanceChargeField;

    private List<PaymentTermsType> paymentTermsField;

    private List<CurrencyExchangeRateInformationType> taxCurrencyInformationField;

    private ExtensionType extensionField;

    private CreditReasonCodeListType creditReasonField;

    private bool creditReasonFieldSpecified;

    private List<DocumentReferenceType> promotionalDealField;

    private DocumentReferenceType invoiceField;

    private DocumentReferenceType deliveryNoteField;

    private DocumentReferenceType orderIdentificationField;

    private DocumentReferenceType receivingAdviceField;

    private DocumentReferenceType orderResponseField;

    private DocumentReferenceType despatchAdviceField;

    private static System.Xml.Serialization.XmlSerializer serializer;

    public InvoiceType()
    {
        this.despatchAdviceField = new DocumentReferenceType();
        this.orderResponseField = new DocumentReferenceType();
        this.receivingAdviceField = new DocumentReferenceType();
        this.orderIdentificationField = new DocumentReferenceType();
        this.deliveryNoteField = new DocumentReferenceType();
        this.invoiceField = new DocumentReferenceType();
        this.promotionalDealField = new List<DocumentReferenceType>();
        this.extensionField = new ExtensionType();
        this.taxCurrencyInformationField = new List<CurrencyExchangeRateInformationType>();
        this.paymentTermsField = new List<PaymentTermsType>();
        this.invoiceAllowanceChargeField = new List<InvoiceAllowanceChargeType>();
        this.invoiceTotalsField = new InvoiceTotalsType();
        this.invoiceLineItemField = new List<InvoiceLineItemType>();
        this.invoicingPeriodField = new TimePeriodType();
        this.sellerField = new InvoicePartyType();
        this.buyerField = new InvoicePartyType();
        this.taxRepresentativeField = new InvoicePartyType();
        this.remitToField = new InvoicePartyType();
        this.payeeField = new InvoicePartyType();
        this.payerField = new InvoicePartyType();
        this.shipToField = new ShipToLogisticsType();
        this.countryOfSupplyOfGoodsField = new ISO3166_1CodeType();
        this.invoiceCurrencyField = new ISO4217_CodeType();
        this.invoiceIdentificationField = new EntityIdentificationType();
    }

    [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified, Order = 0)]
    public EntityIdentificationType invoiceIdentification
    {
        get
        {
            return this.invoiceIdentificationField;
        }
        set
        {
            this.invoiceIdentificationField = value;
        }
    }

    [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified, Order = 1)]
    public ISO4217_CodeType invoiceCurrency
    {
        get
        {
            return this.invoiceCurrencyField;
        }
        set
        {
            this.invoiceCurrencyField = value;
        }
    }

    [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified, Order = 2)]
    public InvoiceTypeCodeListType invoiceType
    {
        get
        {
            return this.invoiceTypeField;
        }
        set
        {
            this.invoiceTypeField = value;
        }
    }

    [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified, Order = 3)]
    public ISO3166_1CodeType countryOfSupplyOfGoods
    {
        get
        {
            return this.countryOfSupplyOfGoodsField;
        }
        set
        {
            this.countryOfSupplyOfGoodsField = value;
        }
    }

    [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified, Order = 4)]
    public ShipToLogisticsType shipTo
    {
        get
        {
            return this.shipToField;
        }
        set
        {
            this.shipToField = value;
        }
    }

    [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified, Order = 5)]
    public InvoicePartyType payer
    {
        get
        {
            return this.payerField;
        }
        set
        {
            this.payerField = value;
        }
    }

    [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified, Order = 6)]
    public InvoicePartyType payee
    {
        get
        {
            return this.payeeField;
        }
        set
        {
            this.payeeField = value;
        }
    }

    [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified, Order = 7)]
    public InvoicePartyType remitTo
    {
        get
        {
            return this.remitToField;
        }
        set
        {
            this.remitToField = value;
        }
    }

    [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified, Order = 8)]
    public InvoicePartyType taxRepresentative
    {
        get
        {
            return this.taxRepresentativeField;
        }
        set
        {
            this.taxRepresentativeField = value;
        }
    }

    [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified, Order = 9)]
    public InvoicePartyType buyer
    {
        get
        {
            return this.buyerField;
        }
        set
        {
            this.buyerField = value;
        }
    }

    [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified, Order = 10)]
    public InvoicePartyType seller
    {
        get
        {
            return this.sellerField;
        }
        set
        {
            this.sellerField = value;
        }
    }

    [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified, Order = 11)]
    public TimePeriodType invoicingPeriod
    {
        get
        {
            return this.invoicingPeriodField;
        }
        set
        {
            this.invoicingPeriodField = value;
        }
    }

    [System.Xml.Serialization.XmlElementAttribute("invoiceLineItem", Form = System.Xml.Schema.XmlSchemaForm.Unqualified, Order = 12)]
    public List<InvoiceLineItemType> invoiceLineItem
    {
        get
        {
            return this.invoiceLineItemField;
        }
        set
        {
            this.invoiceLineItemField = value;
        }
    }

    [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified, Order = 13)]
    public InvoiceTotalsType invoiceTotals
    {
        get
        {
            return this.invoiceTotalsField;
        }
        set
        {
            this.invoiceTotalsField = value;
        }
    }

    [System.Xml.Serialization.XmlElementAttribute("invoiceAllowanceCharge", Form = System.Xml.Schema.XmlSchemaForm.Unqualified, Order = 14)]
    public List<InvoiceAllowanceChargeType> invoiceAllowanceCharge
    {
        get
        {
            return this.invoiceAllowanceChargeField;
        }
        set
        {
            this.invoiceAllowanceChargeField = value;
        }
    }

    [System.Xml.Serialization.XmlElementAttribute("paymentTerms", Form = System.Xml.Schema.XmlSchemaForm.Unqualified, Order = 15)]
    public List<PaymentTermsType> paymentTerms
    {
        get
        {
            return this.paymentTermsField;
        }
        set
        {
            this.paymentTermsField = value;
        }
    }

    [System.Xml.Serialization.XmlElementAttribute("taxCurrencyInformation", Form = System.Xml.Schema.XmlSchemaForm.Unqualified, Order = 16)]
    public List<CurrencyExchangeRateInformationType> taxCurrencyInformation
    {
        get
        {
            return this.taxCurrencyInformationField;
        }
        set
        {
            this.taxCurrencyInformationField = value;
        }
    }

    [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified, Order = 17)]
    public ExtensionType extension
    {
        get
        {
            return this.extensionField;
        }
        set
        {
            this.extensionField = value;
        }
    }

    [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified, Order = 18)]
    public CreditReasonCodeListType creditReason
    {
        get
        {
            return this.creditReasonField;
        }
        set
        {
            this.creditReasonField = value;
        }
    }

    [System.Xml.Serialization.XmlIgnoreAttribute()]
    public bool creditReasonSpecified
    {
        get
        {
            return this.creditReasonFieldSpecified;
        }
        set
        {
            this.creditReasonFieldSpecified = value;
        }
    }

    [System.Xml.Serialization.XmlElementAttribute("promotionalDeal", Form = System.Xml.Schema.XmlSchemaForm.Unqualified, Order = 19)]
    public List<DocumentReferenceType> promotionalDeal
    {
        get
        {
            return this.promotionalDealField;
        }
        set
        {
            this.promotionalDealField = value;
        }
    }

    [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified, Order = 20)]
    public DocumentReferenceType invoice
    {
        get
        {
            return this.invoiceField;
        }
        set
        {
            this.invoiceField = value;
        }
    }

    [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified, Order = 21)]
    public DocumentReferenceType deliveryNote
    {
        get
        {
            return this.deliveryNoteField;
        }
        set
        {
            this.deliveryNoteField = value;
        }
    }

    [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified, Order = 22)]
    public DocumentReferenceType orderIdentification
    {
        get
        {
            return this.orderIdentificationField;
        }
        set
        {
            this.orderIdentificationField = value;
        }
    }

    [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified, Order = 23)]
    public DocumentReferenceType receivingAdvice
    {
        get
        {
            return this.receivingAdviceField;
        }
        set
        {
            this.receivingAdviceField = value;
        }
    }

    [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified, Order = 24)]
    public DocumentReferenceType orderResponse
    {
        get
        {
            return this.orderResponseField;
        }
        set
        {
            this.orderResponseField = value;
        }
    }

    [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified, Order = 25)]
    public DocumentReferenceType despatchAdvice
    {
        get
        {
            return this.despatchAdviceField;
        }
        set
        {
            this.despatchAdviceField = value;
        }
    }

    private static System.Xml.Serialization.XmlSerializer Serializer
    {
        get
        {
            if ((serializer == null))
            {
                serializer = new System.Xml.Serialization.XmlSerializer(typeof(InvoiceType));
            }
            return serializer;
        }
    }

    #region Serialize/Deserialize
    /// <summary>
    /// Serializes current InvoiceType object into an XML document
    /// </summary>
    /// <returns>string XML value</returns>
    public virtual string Serialize()
    {
        System.IO.StreamReader streamReader = null;
        System.IO.MemoryStream memoryStream = null;
        try
        {
            memoryStream = new System.IO.MemoryStream();
            Serializer.Serialize(memoryStream, this);
            memoryStream.Seek(0, System.IO.SeekOrigin.Begin);
            streamReader = new System.IO.StreamReader(memoryStream);
            return streamReader.ReadToEnd();
        }
        finally
        {
            if ((streamReader != null))
            {
                streamReader.Dispose();
            }
            if ((memoryStream != null))
            {
                memoryStream.Dispose();
            }
        }
    }

    /// <summary>
    /// Deserializes workflow markup into an InvoiceType object
    /// </summary>
    /// <param name="xml">string workflow markup to deserialize</param>
    /// <param name="obj">Output InvoiceType object</param>
    /// <param name="exception">output Exception value if deserialize failed</param>
    /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns>
    public static bool Deserialize(string xml, out InvoiceType obj, out System.Exception exception)
    {
        exception = null;
        obj = default(InvoiceType);
        try
        {
            obj = Deserialize(xml);
            return true;
        }
        catch (System.Exception ex)
        {
            exception = ex;
            return false;
        }
    }

    public static bool Deserialize(string xml, out InvoiceType obj)
    {
        System.Exception exception = null;
        return Deserialize(xml, out obj, out exception);
    }

    public static InvoiceType Deserialize(string xml)
    {
        System.IO.StringReader stringReader = null;
        try
        {
            stringReader = new System.IO.StringReader(xml);
            return ((InvoiceType)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader))));
        }
        finally
        {
            if ((stringReader != null))
            {
                stringReader.Dispose();
            }
        }
    }

    /// <summary>
    /// Serializes current InvoiceType object into file
    /// </summary>
    /// <param name="fileName">full path of outupt xml file</param>
    /// <param name="exception">output Exception value if failed</param>
    /// <returns>true if can serialize and save into file; otherwise, false</returns>
    public virtual bool SaveToFile(string fileName, out System.Exception exception)
    {
        exception = null;
        try
        {
            SaveToFile(fileName);
            return true;
        }
        catch (System.Exception e)
        {
            exception = e;
            return false;
        }
    }

    public virtual void SaveToFile(string fileName)
    {
        System.IO.StreamWriter streamWriter = null;
        try
        {
            string xmlString = Serialize();
            System.IO.FileInfo xmlFile = new System.IO.FileInfo(fileName);
            streamWriter = xmlFile.CreateText();
            streamWriter.WriteLine(xmlString);
            streamWriter.Close();
        }
        finally
        {
            if ((streamWriter != null))
            {
                streamWriter.Dispose();
            }
        }
    }

    /// <summary>
    /// Deserializes xml markup from file into an InvoiceType object
    /// </summary>
    /// <param name="fileName">string xml file to load and deserialize</param>
    /// <param name="obj">Output InvoiceType object</param>
    /// <param name="exception">output Exception value if deserialize failed</param>
    /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns>
    public static bool LoadFromFile(string fileName, out InvoiceType obj, out System.Exception exception)
    {
        exception = null;
        obj = default(InvoiceType);
        try
        {
            obj = LoadFromFile(fileName);
            return true;
        }
        catch (System.Exception ex)
        {
            exception = ex;
            return false;
        }
    }

    public static bool LoadFromFile(string fileName, out InvoiceType obj)
    {
        System.Exception exception = null;
        return LoadFromFile(fileName, out obj, out exception);
    }

    public static InvoiceType LoadFromFile(string fileName)
    {
        System.IO.FileStream file = null;
        System.IO.StreamReader sr = null;
        try
        {
            file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read);
            sr = new System.IO.StreamReader(file);
            string xmlString = sr.ReadToEnd();
            sr.Close();
            file.Close();
            return Deserialize(xmlString);
        }
        finally
        {
            if ((file != null))
            {
                file.Dispose();
            }
            if ((sr != null))
            {
                sr.Dispose();
            }
        }
    }
    #endregion
}
28.04.2014

  • Возможно, вам не хватает атрибутов в свойствах. Опубликуйте код EDISalesInvoices.BusinessObjects.Invoice.InvoiceType 28.04.2014
  • Это 650 строк. Я рад предоставить его как-то, но я не думаю, что это поместится в комментарии. :-) Что ты предлагаешь? 29.04.2014
  • Добавьте объявление типа счета к вашему вопросу. (нет в комментарии) 29.04.2014

Новые материалы

Кластеризация: более глубокий взгляд
Кластеризация — это метод обучения без учителя, в котором мы пытаемся найти группы в наборе данных на основе некоторых известных или неизвестных свойств, которые могут существовать. Независимо от..

Как написать эффективное резюме
Предложения по дизайну и макету, чтобы представить себя профессионально Вам не позвонили на собеседование после того, как вы несколько раз подали заявку на работу своей мечты? У вас может..

Частный метод Python: улучшение инкапсуляции и безопасности
Введение Python — универсальный и мощный язык программирования, известный своей простотой и удобством использования. Одной из ключевых особенностей, отличающих Python от других языков, является..

Как я автоматизирую тестирование с помощью Jest
Шутка для победы, когда дело касается автоматизации тестирования Одной очень важной частью разработки программного обеспечения является автоматизация тестирования, поскольку она создает..

Работа с векторными символическими архитектурами, часть 4 (искусственный интеллект)
Hyperseed: неконтролируемое обучение с векторными символическими архитектурами (arXiv) Автор: Евгений Осипов , Сачин Кахавала , Диланта Хапутантри , Тимал Кемпития , Дасвин Де Сильва ,..

Понимание расстояния Вассерштейна: мощная метрика в машинном обучении
В обширной области машинного обучения часто возникает необходимость сравнивать и измерять различия между распределениями вероятностей. Традиционные метрики расстояния, такие как евклидово..

Обеспечение масштабируемости LLM: облачный анализ с помощью AWS Fargate и Copilot
В динамичной области искусственного интеллекта все большее распространение получают модели больших языков (LLM). Они жизненно важны для различных приложений, таких как интеллектуальные..