使用CDATA将XML反序列化为C#模型

时间:2019-05-10 15:08:43

标签: c# xml xml-serialization cdata xml-deserialization

我正在将以下XML反序列化为C#对象

<?xml version="1.0" encoding="utf-8"?>
<Message>
  <Request>
    <FromInfo>
      <Provider>
        <ProviderName><![CDATA[Name]]></ProviderName>
      </Provider>
    </FromInfo>
    <ToInfo>
      <Provider>
        <ProviderID><![CDATA[123]]></ProviderID>
        <ID><![CDATA[1]]></ID>
      </Provider>
    </ToInfo>
  </Request>
  <RS>
    <Add>
      <AccountInfoRecord>
        <UserInfo>
          <FirstName><![CDATA[Some]]></FirstName>
          <LastName><![CDATA[Name]]></LastName>
          <DayPhone><![CDATA[0123456]]></DayPhone>
          <Email><![CDATA[SampleEmail]]></Email>
          <UserAddress>
            <Address1><![CDATA[Address]]></Address1>
            <Address2><![CDATA[Something]]></Address2>
            <City><![CDATA[Oslo]]></City>
            <State />
            <PostalCode><![CDATA[1330]]></PostalCode>
            <Country><![CDATA[some]]></Country>
          </UserAddress>
        </UserInfo>
        <YourUserKey />
      </AccountInfoRecord>
    </Add>
  </RS>
</Message>

我在<State />中遇到错误

但不在<YourUserKey /><State></State>

以下是错误 Unable to cast object of type 'System.Xml.XmlElement' to type 'System.Xml.XmlCDataSection'.

这是模型类


    [XmlElement(ElementName = "State")]
        public XmlCDataSection StateCData
        {
            get
            {
                return !string.IsNullOrEmpty(State)
                    ? new XmlDocument().CreateCDataSection(State) : null;
            }
            set
            {
                State = value?.Value;
            }
        }

我也经历了多个线程,但找不到具体答案。

How do you serialize a string as CDATA using XmlSerializer?

0 个答案:

没有答案