简体   繁体   English

XMLSerializer:查找具有名称和属性值的元素

[英]XMLSerializer : Find element with name and attribute value

I am working to deserialize XML from a third party into a set C# classes.我正在努力将来自第三方的 XML 反序列化为一组 C# 类。 The classes will be used to populate another domain model.这些类将用于填充另一个域模型。 (ETL code) (ETL代码)

Below is a partial example of the XML:下面是 XML 的部分示例:

<Root>
    <Message>
        <Transaction>
            <Header group_element="2TRG00">2TRG212 7</Header>
            <TransactionStructureStandardVersionNumber group_element="2TRG01">98</TransactionStructureStandardVersionNumber>
            <ApplicationSoftwareRevisionLevel group_element="2TRG02"/>
            <TransactionImage group_element="2TRG03"/>
            <AutomationLevel group_element="2TRG04">3</AutomationLevel>
            <TransactionCategory group_element="2TRG05">P</TransactionCategory>
            <PolicyTypeRoutingCode group_element="2TRG06">P</PolicyTypeRoutingCode>
            <LineOfBusinessRoutingCode group_element="2TRG07">HOME</LineOfBusinessRoutingCode>
            <TransactionFunction group_element="2TRG08">FMG</TransactionFunction>
            <ProcessingCycleStatus group_element="2TRG09">B</ProcessingCycleStatus>
            <InitialTransactionMode group_element="2TRG10">N</InitialTransactionMode>
            <SpecialResponseOption group_element="2TRG11">0</SpecialResponseOption>
            <ErrorProcessingOption group_element="2TRG12"/>
            <FormalTransactionAddress group_element="2TRG13">IBM954UNIV</FormalTransactionAddress>
            <InformalTransactionAddress group_element="2TRG14">UNIVERSAL P&amp;C INS CO</InformalTransactionAddress>
            <FormalTransactionAddress group_element="2TRG15"/>
            <InformalTransactionAddress group_element="2TRG16"/>
            <SpecialHandling group_element="2TRG17">WEBCETERA</SpecialHandling>
            <OriginationReferenceInformation group_element="2TRG18"/>
            <TransactionSequenceNumber group_element="2TRG19">8249</TransactionSequenceNumber>
            <DeletedTransactionDate group_element="2TRG20">210217</DeletedTransactionDate>
            <ProcessingCycleNumber group_element="2TRG21">8249</ProcessingCycleNumber>
            <ReferenceTransactionSequenceNumber group_element="2TRG22"/>
            <DeletedTransactionEffectiveDate group_element="2TRG23">210228</DeletedTransactionEffectiveDate>
            <ResponseAutomationLevel group_element="2TRG24"/>
            <CycleBusinessPurpose group_element="2TRG25">REI</CycleBusinessPurpose>
            <SynchronizationField group_element="2TRG26"/>
            <SegmentLevelCode group_element="2TRG27"/>
            <SegmentedTransactionCounter group_element="2TRG28"/>
            <SegmentedTransactionTotalPieces group_element="2TRG29"/>
            <QuoteDate group_element="2TRG30"/>
            <DeletedYear2000LogicCode group_element="2TRG31">A</DeletedYear2000LogicCode>
            <TransactionDate group_element="2TRG32">20210217</TransactionDate>
            <TransactionEffectiveDate group_element="2TRG33">20210228</TransactionEffectiveDate>
        </Transaction>
    </Message>
</Root>

Two things:两件事情:

  1. Some of the element names are duplicated, like InformalTransactionAddress一些元素名称重复,例如 InformalTransactionAddress
  2. Each element has an attribute named "group_element" with a unique value每个元素都有一个名为“group_element”的属性,具有唯一的值

Here is my current class (work in progress)这是我目前的课程(正在进行中)

using Insurance_Carrer_Capture.API.Policy;
using System;
using System.Xml.Serialization;
using AcordAL3XMLParsingLibrary.Extensions;

namespace Insurance_Carrier_Capture.API.Core.Models.Policy
{
    public class Transaction : IPolicyVisitable
    {
        [XmlIgnore]
        public Message Parent{ get; set; }
        [XmlElement("PolicyTypeRoutingCode")] 
        public string PolicyTypeRoutingCode { get; set; }
        [XmlElement("LineOfBusinessRoutingCode")]
        public string LineOfBusinessRoutingCode { get; set; }
        [XmlElement("TransactionFunction")]
        public string TransactionFunction { get; set; }
        [XmlElement("InformalTransactionAddress")] 
        public string InformalTransactionAddressSender { get; set; }
        [XmlElement("TransactionSequenceNumber")]
        public int TransactionSequenceNumber { get; set; }

        [XmlIgnore]
        public DateTime TransactionDate { get; set; }

        [XmlElement("TransactionDate")]
        public String TransactionDateStr
        {
            get { return TransactionDate.DateTimeToDateStr(); }
            set { this.TransactionDate = value.DateStrToDateTime(); }
        }

        [XmlIgnore]
        public DateTime TransactionEffectiveDate { get; set; }
        [XmlElement("TransactionEffectiveDate")]
        public String TransactionEffectiveDateStr
        {
            get { return TransactionEffectiveDate.DateTimeToDateStr(); }
            set { this.TransactionEffectiveDate = value.DateStrToDateTime(); }
        }

        [XmlIgnore]
        public BasicInsuredInformationGroup BasicInsuredInformationGroup { get; set; }
        [XmlIgnore]
        public BasicInsuredInformationExtensionGroup BasicInsuredInformationExtensionGroup { get; set; }

        public void Accept(IPolicyVisitor visitor)
        {
            visitor.VisitTransaction(this);
            //todo: other stuff
        }
    }
}

My question is about the InformalTransactionAddressSender property.我的问题是关于 InformalTransactionAddressSender 属性。 It corresponds to the XML Element InformalTransactionAddress with the group_element value of " 2TRG14 ".它对应于具有“ 2TRG14 ”的group_element值的 XML 元素InformalTransactionAddress How can I make sure that the XMlSerilaizer picks that one and not the one with the value 2TRG16?如何确保 XMlSerilaizer 选择那个而不是值为 2TRG16 的那个?

It seems that the desired element contains inner text, and the other one doesn't.似乎所需的元素包含内部文本,而另一个不包含。

Below I'll show how to create the classes for the XML (complete code is at the end).下面我将展示如何为 XML 创建类(完整代码在最后)。

Given the following XML structure,鉴于以下 XML 结构,

<Root>
    <Message>
        <Transaction>
             ...
        </Transaction>
    </Message>
</Root>

we'll use the following class names:我们将使用以下类名:

  • Root:根:
  • RootMessage: "Root" + "Message"根消息:“根”+“消息”
  • RootMessageTransaction: "RootMessage" + "Transaction" RootMessageTransaction: "RootMessage" + "Transaction"

For any element beneath "Transaction", that contains a property, we'll create a class for it as well.对于“Transaction”下的任何包含属性的元素,我们也将为它创建一个类。 We'll follow a similar naming strategy as above.我们将遵循与上述类似的命名策略。

ex: TransactionFunction will have the following class name: RootMessageTransactionTransactionFunction例如: TransactionFunction将具有以下类名: RootMessageTransactionTransactionFunction

RootMessageTransactionTransactionFunction : RootMessageTransactionTransactionFunction :

public class RootMessageTransactionTransactionFunction
{
    [XmlAttribute(AttributeName = "group_element")]
    public string group_element { get; set; }

    [XmlText]
    public string InnerText { get; set; } = string.Empty;

}

Note : If the element had more properties, we'd add them as well.注意:如果元素有更多属性,我们也会添加它们。

Given:鉴于:

<TransactionFunction group_element="2TRG08">FMG</TransactionFunction>

The inner text is: FMG内文为:FMG

Usage :用法

[XmlElement(ElementName = "TransactionFunction")]
public RootMessageTransactionTransactionFunction TransactionFunction { get; set; } = new RootMessageTransactionTransactionFunction();

Since both FormalTransactionAddress and InformalTransactionAddress occur more than once, we'll use a List for each of them.由于FormalTransactionAddressInformalTransactionAddress出现不止一次,我们将为它们中的每一个使用一个 List。 We'll also add the ability to sort descending on InnerText-which will put the element that contains a value in InnerText in index 0.我们还将添加对 InnerText 进行降序排序的功能——这会将包含 InnerText 值的元素放在索引 0 中。

FormalTransactionAddress will have the following name: RootMessageTransactionFormalTransactionAddress FormalTransactionAddress将具有以下名称: RootMessageTransactionFormalTransactionAddress

RootMessageTransactionFormalTransactionAddress : RootMessageTransactionFormalTransactionAddress :

public class RootMessageTransactionFormalTransactionAddress : IComparable<RootMessageTransactionFormalTransactionAddress>
{
    [XmlAttribute(AttributeName = "group_element")]
    public string group_element { get; set; }

    [XmlText]
    public string InnerText { get; set; } = string.Empty;

    public int CompareTo(RootMessageTransactionFormalTransactionAddress other)
    {
        //sort desc

        if (String.Compare(this.InnerText, other.InnerText, StringComparison.InvariantCultureIgnoreCase) == 0)
        {
            return 0;
        }
        else if (String.Compare(this.InnerText, other.InnerText, StringComparison.InvariantCultureIgnoreCase) > 0)
        {
            return -1; //sort desc
        }
        else
        {
            return 1;
        }
    }
}

Usage :用法

[XmlElement(ElementName = "FormalTransactionAddress")]
public List<RootMessageTransactionFormalTransactionAddress> FormalTransactionAddress { get; set; } = new List<RootMessageTransactionFormalTransactionAddress>();

Below is the complete code needed to deserialize the XML from the OP.下面是从 OP 反序列化 XML 所需的完整代码。

Create a class (name: RootMessageTransaction.cs)创建一个类(名称:RootMessageTransaction.cs)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace XmlSerialization6656
{
    public class RootMessageTransaction
    {
        [XmlElement(ElementName = "ApplicationSoftwareRevisionLevel")]
        public RootMessageTransactionApplicationSoftwareRevisionLevel ApplicationSoftwareRevisionLevel { get; set; } = new RootMessageTransactionApplicationSoftwareRevisionLevel();

        [XmlElement(ElementName = "AutomationLevel")]
        public RootMessageTransactionAutomationLevel AutomationLevel { get; set; } = new RootMessageTransactionAutomationLevel();

        [XmlElement(ElementName = "CycleBusinessPurpose")]
        public RootMessageTransactionCycleBusinessPurpose CycleBusinessPurpose { get; set; } = new RootMessageTransactionCycleBusinessPurpose();

        [XmlElement(ElementName = "DeletedTransactionDate")]
        public RootMessageTransactionDeletedTransactionDate DeletedTransactionDate { get; set; } = new RootMessageTransactionDeletedTransactionDate();

        [XmlElement(ElementName = "DeletedTransactionEffectiveDate")]
        public RootMessageTransactionDeletedTransactionEffectiveDate DeletedTransactionEffectiveDate { get; set; } = new RootMessageTransactionDeletedTransactionEffectiveDate();

        [XmlElement(ElementName = "DeletedYear2000LogicCode")]
        public RootMessageTransactionDeletedYear2000LogicCode DeletedYear2000LogicCode { get; set; } = new RootMessageTransactionDeletedYear2000LogicCode();

        [XmlElement(ElementName = "ErrorProcessingOption")]
        public RootMessageTransactionErrorProcessingOption ErrorProcessingOption { get; set; } = new RootMessageTransactionErrorProcessingOption();

        [XmlElement(ElementName = "FormalTransactionAddress")]
        public List<RootMessageTransactionFormalTransactionAddress> FormalTransactionAddress { get; set; } = new List<RootMessageTransactionFormalTransactionAddress>();

        [XmlElement(ElementName = "Header")]
        public RootMessageTransactionHeader Header { get; set; } = new RootMessageTransactionHeader();

        [XmlElement(ElementName = "InformalTransactionAddress")]
        public List<RootMessageTransactionInformalTransactionAddress> InformalTransactionAddress { get; set; } = new List<RootMessageTransactionInformalTransactionAddress>();

        [XmlElement(ElementName = "InitialTransactionMode")]
        public RootMessageTransactionInitialTransactionMode InitialTransactionMode { get; set; } = new RootMessageTransactionInitialTransactionMode();

        [XmlElement(ElementName = "LineOfBusinessRoutingCode")]
        public RootMessageTransactionLineOfBusinessRoutingCode LineOfBusinessRoutingCode { get; set; } = new RootMessageTransactionLineOfBusinessRoutingCode();

        [XmlElement(ElementName = "OriginationReferenceInformation")]
        public RootMessageTransactionOriginationReferenceInformation OriginationReferenceInformation { get; set; } = new RootMessageTransactionOriginationReferenceInformation();

        [XmlElement(ElementName = "PolicyTypeRoutingCode")]
        public RootMessageTransactionPolicyTypeRoutingCode PolicyTypeRoutingCode { get; set; } = new RootMessageTransactionPolicyTypeRoutingCode();

        [XmlElement(ElementName = "ProcessingCycleNumber")]
        public RootMessageTransactionProcessingCycleNumber ProcessingCycleNumber { get; set; } = new RootMessageTransactionProcessingCycleNumber();

        [XmlElement(ElementName = "ProcessingCycleStatus")]
        public RootMessageTransactionProcessingCycleStatus ProcessingCycleStatus { get; set; } = new RootMessageTransactionProcessingCycleStatus();

        [XmlElement(ElementName = "QuoteDate")]
        public RootMessageTransactionQuoteDate QuoteDate { get; set; } = new RootMessageTransactionQuoteDate();

        [XmlElement(ElementName = "ReferenceTransactionSequenceNumber")]
        public RootMessageTransactionReferenceTransactionSequenceNumber ReferenceTransactionSequenceNumber { get; set; } = new RootMessageTransactionReferenceTransactionSequenceNumber();

        [XmlElement(ElementName = "ResponseAutomationLevel")]
        public RootMessageTransactionResponseAutomationLevel ResponseAutomationLevel { get; set; } = new RootMessageTransactionResponseAutomationLevel();

        [XmlElement(ElementName = "SegmentedTransactionCounter")]
        public RootMessageTransactionSegmentedTransactionCounter SegmentedTransactionCounter { get; set; } = new RootMessageTransactionSegmentedTransactionCounter();

        [XmlElement(ElementName = "SegmentedTransactionTotalPieces")]
        public RootMessageTransactionSegmentedTransactionTotalPieces SegmentedTransactionTotalPieces { get; set; } = new RootMessageTransactionSegmentedTransactionTotalPieces();

        [XmlElement(ElementName = "SegmentLevelCode")]
        public RootMessageTransactionSegmentLevelCode SegmentLevelCode { get; set; } = new RootMessageTransactionSegmentLevelCode();

        [XmlElement(ElementName = "SpecialHandling")]
        public RootMessageTransactionSpecialHandling SpecialHandling { get; set; } = new RootMessageTransactionSpecialHandling();

        [XmlElement(ElementName = "SpecialResponseOption")]
        public RootMessageTransactionSpecialResponseOption SpecialResponseOption { get; set; } = new RootMessageTransactionSpecialResponseOption();

        [XmlElement(ElementName = "SynchronizationField")]
        public RootMessageTransactionSynchronizationField SynchronizationField { get; set; } = new RootMessageTransactionSynchronizationField();

        [XmlElement(ElementName = "TransactionCategory")]
        public RootMessageTransactionTransactionCategory TransactionCategory { get; set; } = new RootMessageTransactionTransactionCategory();

        [XmlElement(ElementName = "TransactionDate")]
        public RootMessageTransactionTransactionDate TransactionDate { get; set; } = new RootMessageTransactionTransactionDate();

        [XmlElement(ElementName = "TransactionEffectiveDate")]
        public RootMessageTransactionTransactionEffectiveDate TransactionEffectiveDate { get; set; } = new RootMessageTransactionTransactionEffectiveDate();

        [XmlElement(ElementName = "TransactionFunction")]
        public RootMessageTransactionTransactionFunction TransactionFunction { get; set; } = new RootMessageTransactionTransactionFunction();

        [XmlElement(ElementName = "TransactionImage")]
        public RootMessageTransactionTransactionImage TransactionImage { get; set; } = new RootMessageTransactionTransactionImage();

        [XmlElement(ElementName = "TransactionSequenceNumber")]
        public RootMessageTransactionTransactionSequenceNumber TransactionSequenceNumber { get; set; } = new RootMessageTransactionTransactionSequenceNumber();

        [XmlElement(ElementName = "TransactionStructureStandardVersionNumber")]
        public RootMessageTransactionTransactionStructureStandardVersionNumber TransactionStructureStandardVersionNumber { get; set; } = new RootMessageTransactionTransactionStructureStandardVersionNumber();

    }

    public class RootMessageTransactionApplicationSoftwareRevisionLevel
    {
        [XmlAttribute(AttributeName = "group_element")]
        public string group_element { get; set; }

        [XmlText]
        public string InnerText { get; set; } = string.Empty;
    }

    public class RootMessageTransactionAutomationLevel
    {
        [XmlAttribute(AttributeName = "group_element")]
        public string group_element { get; set; }

        [XmlText]
        public string InnerText { get; set; } = string.Empty;
    }

    public class RootMessageTransactionCycleBusinessPurpose
    {
        [XmlAttribute(AttributeName = "group_element")]
        public string group_element { get; set; }

        [XmlText]
        public string InnerText { get; set; } = string.Empty;
    }

    public class RootMessageTransactionDeletedTransactionDate
    {
        [XmlAttribute(AttributeName = "group_element")]
        public string group_element { get; set; }

        [XmlText]
        public string InnerText { get; set; } = string.Empty;
    }

    public class RootMessageTransactionDeletedTransactionEffectiveDate
    {
        [XmlAttribute(AttributeName = "group_element")]
        public string group_element { get; set; }

        [XmlText]
        public string InnerText { get; set; } = string.Empty;
    }

    public class RootMessageTransactionDeletedYear2000LogicCode
    {
        [XmlAttribute(AttributeName = "group_element")]
        public string group_element { get; set; }

        [XmlText]
        public string InnerText { get; set; } = string.Empty;
    }

    public class RootMessageTransactionErrorProcessingOption
    {
        [XmlAttribute(AttributeName = "group_element")]
        public string group_element { get; set; }

        [XmlText]
        public string InnerText { get; set; } = string.Empty;
    }

    public class RootMessageTransactionFormalTransactionAddress : IComparable<RootMessageTransactionFormalTransactionAddress>
    {
        [XmlAttribute(AttributeName = "group_element")]
        public string group_element { get; set; }

        [XmlText]
        public string InnerText { get; set; } = string.Empty;

        public int CompareTo(RootMessageTransactionFormalTransactionAddress other)
        {
            //sort desc

            if (String.Compare(this.InnerText, other.InnerText, StringComparison.InvariantCultureIgnoreCase) == 0)
            {
                return 0;
            }
            else if (String.Compare(this.InnerText, other.InnerText, StringComparison.InvariantCultureIgnoreCase) > 0)
            {
                return -1; //sort desc
            }
            else
            {
                return 1;
            }
        }
    }

    public class RootMessageTransactionHeader
    {
        [XmlAttribute(AttributeName = "group_element")]
        public string group_element { get; set; }

        [XmlText]
        public string InnerText { get; set; } = string.Empty;
    }

    public class RootMessageTransactionInformalTransactionAddress : IComparable<RootMessageTransactionInformalTransactionAddress>
    {
        [XmlAttribute(AttributeName = "group_element")]
        public string group_element { get; set; }

        [XmlText]
        public string InnerText { get; set; } = string.Empty;

        public int CompareTo(RootMessageTransactionInformalTransactionAddress other)
        {
            //sort desc

            if (String.Compare(this.InnerText, other.InnerText, StringComparison.InvariantCultureIgnoreCase) == 0)
            {
                return 0;
            }
            else if (String.Compare(this.InnerText, other.InnerText, StringComparison.InvariantCultureIgnoreCase) > 0)
            {
                return -1; //sort desc
            }
            else
            {
                return 1;
            }
        }
    }

    public class RootMessageTransactionInitialTransactionMode
    {
        [XmlAttribute(AttributeName = "group_element")]
        public string group_element { get; set; }

        [XmlText]
        public string InnerText { get; set; } = string.Empty;
    }

    public class RootMessageTransactionLineOfBusinessRoutingCode
    {
        [XmlAttribute(AttributeName = "group_element")]
        public string group_element { get; set; }

        [XmlText]
        public string InnerText { get; set; } = string.Empty;
    }

    public class RootMessageTransactionOriginationReferenceInformation
    {
        [XmlAttribute(AttributeName = "group_element")]
        public string group_element { get; set; }

        [XmlText]
        public string InnerText { get; set; } = string.Empty;
    }

    public class RootMessageTransactionPolicyTypeRoutingCode
    {
        [XmlAttribute(AttributeName = "group_element")]
        public string group_element { get; set; }

        [XmlText]
        public string InnerText { get; set; } = string.Empty;
    }

    public class RootMessageTransactionProcessingCycleNumber
    {
        [XmlAttribute(AttributeName = "group_element")]
        public string group_element { get; set; }

        [XmlText]
        public string InnerText { get; set; } = string.Empty;
    }

    public class RootMessageTransactionProcessingCycleStatus
    {
        [XmlAttribute(AttributeName = "group_element")]
        public string group_element { get; set; }

        [XmlText]
        public string InnerText { get; set; } = string.Empty;
    }

    public class RootMessageTransactionQuoteDate
    {
        [XmlAttribute(AttributeName = "group_element")]
        public string group_element { get; set; }

        [XmlText]
        public string InnerText { get; set; } = string.Empty;
    }

    public class RootMessageTransactionReferenceTransactionSequenceNumber
    {
        [XmlAttribute(AttributeName = "group_element")]
        public string group_element { get; set; }

        [XmlText]
        public string InnerText { get; set; } = string.Empty;
    }

    public class RootMessageTransactionResponseAutomationLevel
    {
        [XmlAttribute(AttributeName = "group_element")]
        public string group_element { get; set; }

        [XmlText]
        public string InnerText { get; set; } = string.Empty;
    }

    public class RootMessageTransactionSegmentedTransactionCounter
    {
        [XmlAttribute(AttributeName = "group_element")]
        public string group_element { get; set; }

        [XmlText]
        public string InnerText { get; set; } = string.Empty;
    }

    public class RootMessageTransactionSegmentedTransactionTotalPieces
    {
        [XmlAttribute(AttributeName = "group_element")]
        public string group_element { get; set; }

        [XmlText]
        public string InnerText { get; set; } = string.Empty;
    }

    public class RootMessageTransactionSegmentLevelCode
    {
        [XmlAttribute(AttributeName = "group_element")]
        public string group_element { get; set; }

        [XmlText]
        public string InnerText { get; set; } = string.Empty;
    }

    public class RootMessageTransactionSpecialHandling
    {
        [XmlAttribute(AttributeName = "group_element")]
        public string group_element { get; set; }

        [XmlText]
        public string InnerText { get; set; } = string.Empty;
    }

    public class RootMessageTransactionSpecialResponseOption
    {
        [XmlAttribute(AttributeName = "group_element")]
        public string group_element { get; set; }

        [XmlText]
        public string InnerText { get; set; } = string.Empty;
    }

    public class RootMessageTransactionSynchronizationField
    {
        [XmlAttribute(AttributeName = "group_element")]
        public string group_element { get; set; }

        [XmlText]
        public string InnerText { get; set; } = string.Empty;
    }

    public class RootMessageTransactionTransactionCategory
    {
        [XmlAttribute(AttributeName = "group_element")]
        public string group_element { get; set; }

        [XmlText]
        public string InnerText { get; set; } = string.Empty;
    }

    public class RootMessageTransactionTransactionDate
    {
        [XmlAttribute(AttributeName = "group_element")]
        public string group_element { get; set; }

        [XmlText]
        public string InnerText { get; set; } = string.Empty;
    }

    public class RootMessageTransactionTransactionEffectiveDate
    {
        [XmlAttribute(AttributeName = "group_element")]
        public string group_element { get; set; }

        [XmlText]
        public string InnerText { get; set; } = string.Empty;
    }

    public class RootMessageTransactionTransactionFunction
    {
        [XmlAttribute(AttributeName = "group_element")]
        public string group_element { get; set; }

        [XmlText]
        public string InnerText { get; set; } = string.Empty;
    }

    public class RootMessageTransactionTransactionImage
    {
        [XmlAttribute(AttributeName = "group_element")]
        public string group_element { get; set; }

        [XmlText]
        public string InnerText { get; set; } = string.Empty;
    }

    public class RootMessageTransactionTransactionSequenceNumber
    {
        [XmlAttribute(AttributeName = "group_element")]
        public string group_element { get; set; }

        [XmlText]
        public string InnerText { get; set; } = string.Empty;
    }

    public class RootMessageTransactionTransactionStructureStandardVersionNumber
    {
        [XmlAttribute(AttributeName = "group_element")]
        public string group_element { get; set; }

        [XmlText]
        public string InnerText { get; set; } = string.Empty;
    }
}

Create a class (name: RootMessage.cs)创建一个类(名称:RootMessage.cs)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace XmlSerialization6656
{
    public class RootMessage
    {
        [XmlElement(ElementName = "Transaction")]
        public RootMessageTransaction Transaction { get; set; } = new RootMessageTransaction();
    }
}

Create a class (name: Root.cs)创建一个类(名称:Root.cs)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace XmlSerialization6656
{
    [XmlRoot(ElementName = "Root", IsNullable = false)]
    public class Root
    {
       [XmlElement(ElementName = "Message")]
       public RootMessage Message { get; set; } = new RootMessage();
    }
}

Create a class (name: HelperXml.cs)创建一个类(名称:HelperXml.cs)

Note: This class is for the serialize and deserialize methods.注意:此类用于序列化和反序列化方法。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace XmlSerialization6656
{
    public class HelperXml
    {
        public static T DeserializeXMLFileToObject<T>(string xmlFilename)
        {
            //Usage: Class1 myClass1 = DeserializeXMLFileToObject<Class1>(xmlFilename);

            T rObject = default(T);

            try
            {
                if (string.IsNullOrEmpty(xmlFilename))
                {
                    return default(T);
                }

                using (System.IO.StreamReader xmlStream = new System.IO.StreamReader(xmlFilename))
                {


                    System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
                    rObject = (T)serializer.Deserialize(xmlStream);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
                throw ex;
            }

            return rObject;
        }


        public static void SerializeObjectToXMLFile(object obj, string xmlFilename)
        {
            //Usage: Class1 myClass1 = new Class1();
            //SerializeObjectToXMLFile(myClass1, xmlFilename);

            try
            {
                if (string.IsNullOrEmpty(xmlFilename))
                {
                    return;
                }//if

                System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings();
                settings.OmitXmlDeclaration = false;
                settings.Indent = true;
                settings.NewLineHandling = System.Xml.NewLineHandling.Entitize;

                using (System.Xml.XmlWriter xmlWriter = System.Xml.XmlWriter.Create(xmlFilename, settings))
                {
                    //specify namespaces
                    System.Xml.Serialization.XmlSerializerNamespaces ns = new System.Xml.Serialization.XmlSerializerNamespaces();
                    ns.Add(string.Empty, "urn:none");

                    //create new instance
                    System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(obj.GetType());

                    //write XML to file
                    serializer.Serialize(xmlWriter, obj, ns);

                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
                throw ex;
            }
        }
    }
}

Usage :用法

//deserialize - get XML from file
Root root = HelperXml.DeserializeXMLFileToObject<Root>(xmlFilename);

//serialize - save XML to file
HelperXml.SerializeObjectToXMLFile(root, xmlFilename);

Example :示例

private void GetXmlData(string xmlFilename)
{
    //get XML
    Root root = HelperXml.DeserializeXMLFileToObject<Root>(xmlFilename);

    Debug.WriteLine("Header: " + root.Message.Transaction.Header.InnerText);

    //sort
    root.Message.Transaction.FormalTransactionAddress.Sort();

    foreach (var fta in root.Message.Transaction.FormalTransactionAddress)
    {
        Debug.WriteLine("FormalTransactionAddress: group_element: " + fta.group_element + " InnerText: " + fta.InnerText);
    }

    //sort
    root.Message.Transaction.InformalTransactionAddress.Sort();

    foreach (var fta in root.Message.Transaction.InformalTransactionAddress)
    {
        Debug.WriteLine("InformalTransactionAddress: group_element: " + fta.group_element + " InnerText: " + fta.InnerText);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM