反序列化无法填充对象中的元素
本文关键字:元素 对象 填充 反序列化 | 更新日期: 2023-09-27 18:12:26
关于将xml文件反序列化为对象,我有几个问题,这个问题已经困扰了我将近两天了。我感谢任何人能提供的任何帮助!
我使用xsd.exe从模式文件生成c#类。然后,我使用XMLExplorer创建了一个示例XML文件。这是一个正确的假设,如果我保存样本文件,不变,与样本文本值,并将其反序列化到适当的c#类,它"应该"读取值,并把它们放入适当的对象?
XMLDeserializer是否要求XML文件中存在所有元素,或者XML文件包含缺失的元素,但仍然可以正确地反序列化(例如,通过在缺失的属性中放置空值)??
我读到XMLSerializer只检查三个错误,我已经通过标记xmlroot和删除损坏的URL来解决这些错误。我的代码运行,但我得到null为"InvokingBusinessActivity"answers"乘客"和其他属性。
这是我的反序列化代码。
IATA_PassengerConformanceIdentifyRQ localIataReq = new IATA_PassengerConformanceIdentifyRQ();
XmlSerializer deserializer = new XmlSerializer(localIataReq.GetType());
StreamReader reader = new StreamReader("C:''Airports''Projects_Current''Multi-channel''Dev''Integration''MCUniversalBagDropAPITester''IataXmlSchemas''Test Xml Files''PassengerIdentifyRequest.xml");
XmlRootAttribute xRoot = new XmlRootAttribute();
xRoot.ElementName = "IATA_PassengerConformanceIdentifyRQ";
xRoot.IsNullable = false;
localIataReq = (IATA_PassengerConformanceIdentifyRQ)deserializer.Deserialize(reader);
reader.Close();
这是我从XSD生成的类。因为它大约有1000行,所以它被缩减了:
using System.Xml.Serialization;
//
// This source code was auto-generated by xsd, Version=4.0.30319.1.
//
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="http://www.iata.org/IATA/2007/00")]
[System.Xml.Serialization.XmlRootAttribute("IATA_PassengerConformanceIdentifyRQ", IsNullable = false)] /* I commented out and obfuscated defective Namespace="http://ww w.iat a.org/IATA/2007/00",*/
public partial class IATA_PassengerConformanceIdentifyRQ
{
private SourceType[] originatorField;
private BusinessActivityType invokingBusinessActivityField;
private IATA_PassengerConformanceIdentifyRQPassenger passengerField;
private string echoTokenField;
private System.DateTime timeStampField;
private bool timeStampFieldSpecified;
private IATA_PassengerConformanceIdentifyRQTarget targetField;
private decimal versionField;
private string transactionIdentifierField;
private string sequenceNmbrField;
private IATA_PassengerConformanceIdentifyRQTransactionStatusCode transactionStatusCodeField;
private bool transactionStatusCodeFieldSpecified;
private bool retransmissionIndicatorField;
private bool retransmissionIndicatorFieldSpecified;
private string correlationIDField;
private bool asynchronousAllowedIndField;
private bool asynchronousAllowedIndFieldSpecified;
public IATA_PassengerConformanceIdentifyRQ() {
this.targetField = IATA_PassengerConformanceIdentifyRQTarget.Production;
}
/// <remarks/>
[System.Xml.Serialization.XmlArrayItemAttribute("Source", IsNullable=false)]
public SourceType[] Originator {
get {
return this.originatorField;
}
set {
this.originatorField = value;
}
}
/// <remarks/>
public BusinessActivityType InvokingBusinessActivity {
get {
return this.invokingBusinessActivityField;
}
set {
this.invokingBusinessActivityField = value;
}
}
等等……
下面是VS2010 XMLSchema Explorer创建的测试文件。为简单起见,删除了"复杂类型"的重复元素。损坏的URL也被删除,我将xml版本添加到顶部以修复序列化问题。
<?xml version="1.0" encoding="utf-8"?>
<IATA_PassengerConformanceIdentifyRQ>
<!-- EchoToken="EchoToken1" TimeStamp="1900-01-01T01:01:01-06:00" Target="Production" Version="1" TransactionIdentifier="TransactionIdentifier1" SequenceNmbr="32" TransactionStatusCode="Start" PrimaryLangID="en" AltLangID="en" RetransmissionIndicator="true" CorrelationID="CorrelationID1" AsynchronousAllowedInd="true" xmlns="ht tp: // www . iata.org/IATA/2007/00" -->
<Originator>
<Source AgentSine="AgentSine1" PseudoCityCode="PseudoCityCode1" ISOCountry="ISOCountry1" ISOCurrency="ISOCurrency1" AgentDutyCode="AgentDutyCode1" AirlineVendorID="AirlineVendorID1" AirportCode="AirportCode1" FirstDepartPoint="Fi1" ERSP_UserID="ERSP_UserID1" TerminalID="TerminalID1">
<RequestorID MessagePassword="MessagePassword1" URL="http://uri1" Type="Type1" Instance="Instance1" ID="ID1" ID_Context="ID_Context1">
<CompanyName CompanyShortName="CompanyShortName1" TravelSector="TravelSector1" Code="Code1" CodeContext="CodeContext1">CompanyName1</CompanyName>
</RequestorID>
<Position Latitude="Latitude1" Longitude="Longitude1" Altitude="Altitude1" AltitudeUnitOfMeasureCode="AltitudeUnitOfMeasureCode1" />
<BookingChannel Type="Type1" Primary="true">
<CompanyName CompanyShortName="CompanyShortName1" TravelSector="TravelSector1" Code="Code1" CodeContext="CodeContext1">CompanyName1</CompanyName>
</BookingChannel>
</Source>
</Originator>
<InvokingBusinessActivity Code="06">Baggage Processing</InvokingBusinessActivity>
<Passenger>
<GUID>GUID1</GUID>
<NativeID>NativeID1</NativeID>
<Name ShareSynchInd="Yes" ShareMarketInd="Yes" NameType="NameType1">
<NamePrefix>NamePrefix1</NamePrefix>
<NamePrefix>NamePrefix2</NamePrefix>
<NamePrefix>NamePrefix3</NamePrefix>
<GivenName>GivenName1</GivenName>
<GivenName>GivenName2</GivenName>
<GivenName>GivenName3</GivenName>
<MiddleName>MiddleName1</MiddleName>
<MiddleName>MiddleName2</MiddleName>
<MiddleName>MiddleName3</MiddleName>
<SurnamePrefix>SurnamePrefix1</SurnamePrefix>
<Surname>Surname1</Surname>
<NameSuffix>NameSuffix1</NameSuffix>
<NameSuffix>NameSuffix2</NameSuffix>
<NameSuffix>NameSuffix3</NameSuffix>
<NameTitle>NameTitle1</NameTitle>
<NameTitle>NameTitle2</NameTitle>
<NameTitle>NameTitle3</NameTitle>
</Name>
<CustomerLoyalty ShareSynchInd="Yes" ShareMarketInd="Yes" ProgramID="ProgramID1" MembershipID="MembershipID1" TravelSector="TravelSector1" LoyalLevel="LoyalLevel1" SingleVendorInd="SingleVndr" SignupDate="1900-01-01" EffectiveDate="1900-01-01" ExpireDate="1900-01-01" RPH="RPH1" VendorCode="VendorC1 VendorC2 VendorC3 " />
<CustomerLoyalty ShareSynchInd="No" ShareMarketInd="No" ProgramID="ProgramID2" MembershipID="MembershipID2" TravelSector="TravelSector2" LoyalLevel="LoyalLevel2" SingleVendorInd="Alliance" SignupDate="0001-01-01" EffectiveDate="0001-01-01" ExpireDate="0001-01-01" RPH="RPH2" VendorCode="VendorC4 VendorC5 VendorC6 " />
<BoardingPass>
<ForIndividualAirlineUse>ForIndividualAirlineUse1</ForIndividualAirlineUse>
<DigitalSignature Type="1">DigitalSignature1</DigitalSignature>
</BoardingPass>
<Segment>
<PNR URL="http://uri1" Type="Type1" Instance="Instance1" ID="ID1" ID_Context="ID_Context1" />
<NativeID>NativeID1</NativeID>
<Flight>
<NativeID>NativeID1</NativeID>
<OperatingCarrier>Op1</OperatingCarrier>
<FlightNumber>FlightNumber1</FlightNumber>
<OperationalSuffix>OperationalSuffix1</OperationalSuffix>
<MarketingCarrier>Ma1</MarketingCarrier>
<ScheduledDateOfDeparture>1900-01-01</ScheduledDateOfDeparture>
<ScheduledTimeOfDeparture>01:01:01</ScheduledTimeOfDeparture>
<ScheduledDateOfArrival>1900-01-01</ScheduledDateOfArrival>
<ScheduledTimeOfArrival>01:01:01</ScheduledTimeOfArrival>
</Flight>
<DepartureAirport>
<AirportCode>Air1</AirportCode>
<SourceIndicator>1</SourceIndicator>
</DepartureAirport>
<ArrivalAirport>
<AirportCode>Air1</AirportCode>
<SourceIndicator>1</SourceIndicator>
</ArrivalAirport>
<Cabin>Cabin1</Cabin>
<SeatNumber>SeatNumber1</SeatNumber>
<CheckInSequenceNumber>Chec1</CheckInSequenceNumber>
</Segment>
</Passenger>
</IATA_PassengerConformanceIdentifyRQ>
我做错了什么,我不确定到底是什么!有人能给点建议吗??
试试下面的代码。我做了一些抽查错误,但仍然可能有一些问题。我从一个不同的文件名读取XML,所以你需要回到你原来的文件名。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = @"c:'temp'test.xml";
static void Main(string[] args)
{
IATA_PassengerConformanceIdentifyRQ localIataReq = new IATA_PassengerConformanceIdentifyRQ();
XmlSerializer deserializer = new XmlSerializer(localIataReq.GetType());
StreamReader reader = new StreamReader(FILENAME);
XmlRootAttribute xRoot = new XmlRootAttribute();
xRoot.ElementName = "IATA_PassengerConformanceIdentifyRQ";
xRoot.IsNullable = false;
localIataReq = (IATA_PassengerConformanceIdentifyRQ)deserializer.Deserialize(reader);
reader.Close();
XmlSerializer serializer = new XmlSerializer(typeof(IATA_PassengerConformanceIdentifyRQ));
StreamWriter writer = new StreamWriter(@"c:'temp'test1.xml");
serializer.Serialize(writer, localIataReq);
writer.Flush();
writer.Close();
writer.Dispose();
}
}
[XmlRoot("IATA_PassengerConformanceIdentifyRQ")]
public partial class IATA_PassengerConformanceIdentifyRQ
{
[XmlElement("Originator")]
public Originator originator { get; set;}
[XmlElement("InvokingBusinessActivity")]
public InvokingBusinessActivity invokingBusinessActivity { get; set; }
[XmlElement("Passenger")]
public Passenger passenger { get; set; }
}
[XmlRoot("Originator")]
public partial class Originator
{
[XmlElement("Source")]
public Source source { get; set;}
}
[XmlRoot("Source")]
public class Source
{
[XmlAttribute("AgentSine")]
public string agentSine { get; set; }
[XmlAttribute("PseudoCityCode")]
public string pseudoCityCode { get; set; }
[XmlAttribute("ISOCountry")]
public string iSOCountry { get; set; }
[XmlAttribute("ISOCurrency")]
public string iSOCurrency { get; set; }
[XmlAttribute("AgentDutyCode")]
public string agentDutyCode { get; set; }
[XmlAttribute("AirlineVendorID")]
public string airlineVendorID { get; set; }
[XmlAttribute("AirportCode")]
public string airportCode { get; set; }
[XmlAttribute("FirstDepartPoint")]
public string firstDepartPoint { get; set; }
[XmlAttribute("ERSP_UserID")]
public string eRSP_UserID { get; set; }
[XmlAttribute("TerminalID")]
public string terminalID { get; set; }
[XmlElement("RequestorID")]
public RequestorID requestorID { get; set; }
[XmlElement("Position")]
public Position position { get; set; }
[XmlElement("BookingChannel")]
public BookingChannel bookingChannel { get; set; }
}
[XmlRoot("RequestorID")]
public class RequestorID
{
[XmlAttribute("MessagePassword")]
public string messagePassword { get; set; }
[XmlAttribute("URL")]
public string url { get; set; }
[XmlAttribute("Type")]
public string _type { get; set; }
[XmlAttribute("Instance")]
public string instance { get; set; }
[XmlAttribute("ID")]
public string id { get; set; }
[XmlAttribute("ID_Context")]
public string id_Context { get; set; }
}
[XmlRoot("Position")]
public partial class Position
{
[XmlAttribute("Latitude")]
public string latitude { get; set; }
[XmlAttribute("Longitude")]
public string longitude { get; set; }
[XmlAttribute("Altitude")]
public string altitude { get; set; }
[XmlAttribute("AltitudeUnitOfMeasureCode")]
public string altitudeUnitOfMeasureCode { get; set; }
}
[XmlRoot("BookingChannel")]
public class BookingChannel
{
[XmlAttribute("Type")]
public string _type { get; set; }
[XmlAttribute("Primary")]
public Boolean primary { get; set; }
[XmlElement("CompanyName")]
public CompanyName companyName { get; set; }
}
[XmlRoot("CompanyName")]
public class CompanyName
{
[XmlAttribute("CompanyShortName")]
public string companyShortName { get; set; }
[XmlAttribute("TravelSector")]
public string travelSector { get; set; }
[XmlAttribute("Code")]
public string code { get; set; }
[XmlAttribute("CodeContext")]
public string codeContext { get; set; }
[XmlText]
public string name { get; set; }
}
[XmlRoot("InvokingBusinessActivity")]
public class InvokingBusinessActivity
{
[XmlAttribute("Code")]
public string code { get; set; }
[XmlText]
public string value { get; set; }
}
[XmlRoot("Passenger")]
public class Passenger
{
[XmlElement("GUID")]
public Value guid { get; set; }
[XmlElement("NativeID")]
public Value nativeID { get; set; }
[XmlElement("Name")]
public Name name { get; set; }
[XmlElement("CustomerLoyalty")]
public List<CustomerLoyalty> customerLoyalty { get; set; }
[XmlElement("BoardingPass")]
public BoardingPass boardingPass { get; set; }
[XmlElement("Segment")]
public Segment segment { get; set; }
}
public class Value
{
[XmlText]
public string value { get; set; }
}
[XmlRoot("Name")]
public class Name
{
[XmlAttribute("ShareSynchInd")]
public string shareSynchInd { get; set; }
[XmlAttribute("ShareMarketInd")]
public string shareMarketInd { get; set; }
[XmlAttribute("NameType")]
public string NameType { get; set; }
[XmlElement("NamePrefix")]
public List<string> namePrefix { get; set; }
[XmlElement("GivenName")]
public List<string> givenName { get; set; }
[XmlElement("MiddleName")]
public List<string> middleName { get; set; }
[XmlElement("SurnamePrefix")]
public List<string> surnamePrefix { get; set; }
[XmlElement("Surname")]
public List<string> surname { get; set; }
[XmlElement("NameSuffix")]
public string nameSuffix { get; set; }
[XmlElement("NameTitle")]
public string nameTitle { get; set; }
}
[XmlRoot("CustomerLoyalty")]
public class CustomerLoyalty
{
[XmlAttribute("ShareSynchInd")]
public string shareSynchInd { get; set; }
[XmlAttribute("ShareMarketInd")]
public string shareMarketInd { get; set; }
[XmlAttribute("ProgramID")]
public string programID { get; set; }
[XmlAttribute("MembershipID")]
public string membershipID { get; set; }
[XmlAttribute("TravelSector")]
public string travelSector { get; set; }
[XmlAttribute("LoyalLevel")]
public string loyalLevel { get; set; }
[XmlAttribute("SingleVendorInd")]
public string singleVendorInd { get; set; }
[XmlAttribute("SignupDate")]
public DateTime signupDate { get; set; }
[XmlAttribute("EffectiveDate")]
public DateTime effectiveDate { get; set; }
[XmlAttribute("ExpireDate")]
public DateTime expireDate { get; set; }
[XmlAttribute("RPH")]
public string rph { get; set; }
[XmlAttribute("VendorCode")]
public string vendorCode { get; set; }
}
[XmlRoot("BoardingPass")]
public class BoardingPass
{
[XmlElement("ForIndividualAirlineUse")]
public string forIndividualAirlineUse { get; set; }
[XmlElement("DigitalSignature")]
public DigitalSignature digitalSignature { get; set; }
}
[XmlRoot("DigitalSignature")]
public class DigitalSignature
{
[XmlAttribute("Type")]
public int _type { get; set; }
[XmlText]
public string value { get; set; }
}
[XmlRoot("Segment")]
public class Segment
{
[XmlElement("PNR")]
public PNR pnr { get; set; }
[XmlElement("NativeID")]
public string nativeID { get; set; }
[XmlElement("Flight")]
public Flight flight { get; set; }
[XmlElement("DepartureAirport")]
public Airport departureAirport { get; set; }
[XmlElement("ArrivalAirport")]
public Airport arrivalAirport { get; set; }
[XmlElement("Cabin")]
public string cabin { get; set; }
[XmlElement("SeatNumber")]
public string seatNumber { get; set; }
[XmlElement("CheckInSequenceNumber")]
public string checkInSequenceNumber { get; set; }
}
[XmlRoot("PNR")]
public class PNR
{
[XmlAttribute("URL")]
public string url { get; set; }
[XmlAttribute("Type")]
public string _type { get; set; }
[XmlAttribute("Instance")]
public string Instance { get; set; }
[XmlAttribute("ID")]
public string id { get; set; }
[XmlAttribute("ID_Context")]
public string id_Context { get; set; }
}
[XmlRoot("Flight")]
public class Flight
{
[XmlElement("NativeID")]
public string nativeID { get; set; }
[XmlElement("OperatingCarrier")]
public string operatingCarrier { get; set; }
[XmlElement("FlightNumber")]
public string flightNumber { get; set; }
[XmlElement("OperationalSuffix")]
public string operationalSuffix { get; set; }
[XmlElement("MarketingCarrier")]
public string marketingCarrier { get; set; }
[XmlElement("ScheduledDateOfDeparture")]
public DateTime scheduledDateOfDeparture { get; set; }
[XmlElement("ScheduledTimeOfDeparture")]
public DateTime scheduledTimeOfDeparture { get; set; }
[XmlElement("ScheduledDateOfArrival")]
public DateTime scheduledDateOfArrival { get; set; }
[XmlElement("ScheduledTimeOfArrival")]
public DateTime scheduledTimeOfArrival { get; set; }
}
public class Airport
{
[XmlElement("AirportCode")]
public string airportCode { get; set; }
[XmlElement("SourceIndicator")]
public int sourceIndicator { get; set; }
}
}
好的。奇怪。我在不同的开发机器上创建了一个全新的项目,并使用所有干净的XSD->CS和XSD->Sample XML运行了整个过程,这段代码运行得很好。所以我想我删除了这个问题,或者有人可以沿着"重新开始"的路线发布答案。我确定的唯一不同之处是,我将标头标记从XMLSchemaExplorer拖到设计器工作界面,而不是拖到IATA_PASSENGERCONFORMANCEIDENTIFYRQ元素。这产生了一个巨大的分支树,而不是单个节点。这可能会导致问题,但可能会发生其他事情:我怀疑旧项目上的VS2010保留了对早期版本类的引用,或者在备份文件夹中引用了错误的版本。