#c# #xml-parsing #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 Pamp;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. Он соответствует XML-элементу InformalTransactionAddress со значением group_element «2TRG14«. Как я могу убедиться, что XMlSerilaizer выберет именно этот, а не тот, у которого значение 2TRG16?
Ответ №1:
Похоже, что нужный элемент содержит внутренний текст, а другой-нет.
Ниже я покажу, как создавать классы для XML (полный код находится в конце).
Учитывая следующую структуру XML,
<Root>
<Message>
<Transaction>
...
</Transaction>
</Message>
</Root>
мы будем использовать следующие имена классов:
- Корень:
- Корневое сообщение: «Корень» «Сообщение»
- RootMessageTransaction: «Корневое сообщение» «Транзакция»
Для любого элемента под «Транзакцией», который содержит свойство, мы также создадим для него класс. Мы будем следовать аналогичной стратегии именования, как описано выше.
пример: TransactionFunction
будет иметь следующее имя класса: RootMessageTransactionTransactionFunction
Функция rootmessagetransactionтранзакции:
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>
The inner text is: 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. 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.
FormalTransactionAddress
будет иметь следующее название: RootMessageTransactionFormalTransactionAddress
Rootmessagetransactionформальный адрес транзакции:
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>();
Ниже приведен полный код, необходимый для десериализации 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)
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;
}
}
}
}
Использование:
//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);
}
}