开发者

How can I get XmlSerializer deserialize attributes from multiple namespaces? [closed]

开发者 https://www.devze.com 2022-12-28 11:07 出处:网络
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time,or an extraordinarily narrow situation that is not generally applic
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicab开发者_StackOverflow中文版le to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center. Closed 10 years ago.

I have a schema from a third party that I've generated c# objects from using Xsd2Code (other options like xsd.exe, xmlspy etc either crashed or spewed 40mb of code that required their library to work)

Anyway, here's an example of a problem element from the schema:

<xsd:schema xmlns:ns1="something" xmlns:ns2="somethinelse" targetNamespace="something">

  <xsd:complexType name="someType">
    <xsd:sequence>
      <xsd:element ref="element1" />
      <xsd:element ref="ns2:element2" />
    </xsd:sequence>
  </xsd:complexType>

 </xsd:schema>

The generated wrapper class looks like this:

[XmlType(Namespace="something")]
[XmlRoot("someType", Namespace="something", IsNullable=false)]
public partial class SomeType {
  public string Element1 { get; set; }

  [XmlElement(Namespace="somethinelse")]
  public string Element2 { get; set; }
}

Example xml using said schema:

<someType>
  <element1>SomeValue</element1>
  <ns2:element2>SomeValue2</element2>
</someType>

(Any errors are my typing the example. the schema is valid and un-changeable)

And now for the problem. when I try to deserialize the xml like so:

XmlSerializer ser = new XmlSerializer(typeof(SomeType));
XmlReader reader = XmlReader.Create(new StringReader(xmlString))
SomeType obj = (SomeType)ser.Deserialize(reader)

The generated objects serialize correctly, adding the "ns2" to elements that need it. However, when deserializing, element1 gets set and element2 is left null.


The sample data we were provided with had a typeo in the namespace which was causing it to deserialize wrong. Go figure.

0

精彩评论

暂无评论...
验证码 换一张
取 消