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

Posted

技术标签:

【中文标题】XMLSerializer : 查找具有名称和属性值的元素【英文标题】:XMLSerializer : Find element with name and attribute value 【发布时间】:2021-10-06 21:00:44 【问题描述】:

我正在努力将第三方的 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>

两件事:

    某些元素名称重复,例如 InformalTransactionAddress 每个元素都有一个名为“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 的那个?

【问题讨论】:

【参考方案1】:

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

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

鉴于以下 XML 结构,

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

我们将使用以下类名:

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

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

例如: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 出现不止一次,我们将为它们中的每一个使用一个列表。我们还将添加对 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, other.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, 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;
    

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

【讨论】:

以上是关于XMLSerializer : 查找具有名称和属性值的元素的主要内容,如果未能解决你的问题,请参考以下文章

XmlSerializer 和可为空的属性

XmlSerializer和可空属性

我可以让 XmlSerializer 在反序列化时忽略命名空间吗?

Grails:查找具有列表属性的对象,其中包含具有给定属性值的对象

C# XMLSerializer 将错误的类型反序列化为 List

按属性查找元素