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

如何解决XMLSerializer:查找具有名称和属性值的元素

我正在努力将来自第三方的 XML 反序列化为一组 C# 类。这些类将用于填充另一个域模型。 (ETL代码)

以下是 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>

两件事:

  1. 某些元素名称重复,例如 InformalTransactionAddress
  2. 每个元素都有一个名为“group_element”且具有唯一值的属性

这是我当前的课程(正在进行中)

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
        }
    }
}

我的问题是关于 InformalTransactionAddressSender 属性。它对应于 group_element 值为“2TRG14”的 XML 元素 InformalTransactionAddress。如何确保 XMlSerilaizer 选择那个而不是值为 2TRG16 的那个?

解决方法

似乎所需元素包含内部文本,而另一个没有。

下面我将展示如何为 XML 创建类(完整代码在最后)。

鉴于以下 XML 结构,

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

我们将使用以下类名:

  • 根:
  • RootMessage:“根”+“消息”
  • RootMessageTransaction:“RootMessage”+“交易”

对于“Transaction”下的任何包含属性的元素,我们也将为它创建一个类。我们将遵循与上述类似的命名策略。

例如:TransactionFunction 将具有以下类名:RootMessageTransactionTransactionFunction

RootMessageTransactionTransactionFunction

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

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

}

注意:如果元素有更多属性,我们也会添加它们。

给定:

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

内文为:FMG

用法

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

由于 FormalTransactionAddressInformalTransactionAddress 都出现不止一次,我们将为它们中的每一个使用一个 List。我们还将添加对 InnerText 进行降序排序的功能——这会将包含 InnerText 值的元素放在索引 0 中。

FormalTransactionAddress 将具有以下名称: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,StringComparison.InvariantCultureIgnoreCase) > 0)
        {
            return -1; //sort desc
        }
        else
        {
            return 1;
        }
    }
}

用法

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

以下是从 OP 反序列化 XML 所需的完整代码。

创建类(名称: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,StringComparison.InvariantCultureIgnoreCase) == 0)
            {
                return 0;
            }
            else if (String.Compare(this.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,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;
    }
}

创建类(名称: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();
    }
}

创建类(名称: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();
    }
}

创建类(名称:HelperXml.cs)

注意:该类用于序列化和反序列化方法。

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;
            }
        }
    }
}

用法

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

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

示例

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);
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res