Deserializing cXML to C# Class

三世轮回 提交于 2020-08-02 13:08:12

问题


I'm trying to deserialize a cXML string into C# classes. However, when deserializing, I can't seem to get anything other than the root element to deserialize. How to Deserialize XML document seemed to provide the most help, and using that example I've managed to deserialize the root cXML tag, but this doesn't work on the nested object PunchOutSetupRequest which is the object I really need deserialized.

My question, before showing you the wall of code, is how can I properly deserialize these objects to the cXML classes defined below without changing the cXML.cs file? Since this is a standard I'd prefer not to edit it unless I absolutely have to. My code is fair game. Thank you in advance for any help since I know this topic is covered far and wide across SO.

I have this XSD file for cXML that I've used the xsd.exe tool to convert into C# classes. I won't paste the whole schema here to avoid diluting the question, but you can go to cxml.org if you need a more complete picture.

My Code for the cXML which just deserializes the attributes and doesn't contain Header or Request objects defined in the cXML:

using (TextReader reader = new StringReader(text))
            {
                try
                {
                    XmlRootAttribute xRoot = new XmlRootAttribute();
                    xRoot.ElementName = "cXML";
                    xRoot.IsNullable = true;
                    var serializer = new XmlSerializer(typeof(cXML), xRoot);
                    cxml = (cXML)serializer.Deserialize(reader);
                }
                catch (Exception ex)
                {
                    string r = "";
                }
            }

My code for the PunchOutSetupRequest deserialization. This one throws an error when it sees cXML as the root node despite me setting the xRoot element to PunchOutSetupRequest.

using (TextReader reader = new StringReader(text))
            {
                try
                {
                    XmlRootAttribute xRoot = new XmlRootAttribute();
                    xRoot.ElementName = "PunchOutSetupRequest";
                    xRoot.IsNullable = true;
                    var serializer = new XmlSerializer(typeof(PunchOutSetupRequest), xRoot);
                    PunchOutSetupRequest request;
                    request = (PunchOutSetupRequest)serializer.Deserialize(reader);
                }
                catch (Exception ex)
                {
                    string r = "";
                }
            }

text variable value (data redacted):

<?xml version = '1.0' encoding = 'UTF-8'?>
<!DOCTYPE cXML SYSTEM "http://xml.cxml.org/schemas/cXML/1.1.007/cXML.dtd">
<cXML version="1.1.007" xml:lang="en-US" payloadID="" timestamp="2016-01-    04T03:21:32-05:00">
   <Header>
      <From>
         <Credential domain="">
            <Identity></Identity>
         </Credential>
      </From>
      <To>
         <Credential domain="">
            <Identity></Identity>
         </Credential>
      </To>
      <Sender>
         <Credential domain="">
            <Identity></Identity>
            <SharedSecret></SharedSecret>
         </Credential>
         <UserAgent></UserAgent>
      </Sender>
   </Header>
   <Request>
      <PunchOutSetupRequest operation="create">
         <BuyerCookie></BuyerCookie>
         <Extrinsic name="User"></Extrinsic>
         <BrowserFormPost>
            <URL></URL>
         </BrowserFormPost>
         <Contact>
            <Name xml:lang="en-US"></Name>
            <Email></Email>
         </Contact>
         <SupplierSetup>
            <URL></URL>
         </SupplierSetup>
      </PunchOutSetupRequest>
   </Request>
</cXML>

cXML Class Generated by xsd.exe (fragmented)

[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://tempuri.org/cXML")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://tempuri.org/cXML", IsNullable = false)]
public partial class cXML
{

private object[] itemsField;

private string versionField;

private string payloadIDField;

private string timestampField;

private string langField;

public cXML()
{
    this.versionField = "1.1.010";
}

/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("Header", typeof(Header))]
[System.Xml.Serialization.XmlElementAttribute("Message", typeof(Message))]
[System.Xml.Serialization.XmlElementAttribute("Request", typeof(Request))]
[System.Xml.Serialization.XmlElementAttribute("Response", typeof(Response))]
public object[] Items
{
    get
    {
        return this.itemsField;
    }
    set
    {
        this.itemsField = value;
    }
}

/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
[System.ComponentModel.DefaultValueAttribute("1.1.010")]
public string version
{
    get
    {
        return this.versionField;
    }
    set
    {
        this.versionField = value;
    }
}

/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string payloadID
{
    get
    {
        return this.payloadIDField;
    }
    set
    {
        this.payloadIDField = value;
    }
}

/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string timestamp
{
    get
    {
        return this.timestampField;
    }
    set
    {
        this.timestampField = value;
    }
}

/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(Form = System.Xml.Schema.XmlSchemaForm.Qualified, Namespace = "http://www.w3.org/XML/1998/namespace")]
public string lang
{
    get
    {
        return this.langField;
    }
    set
    {
        this.langField = value;
    }
}
}    

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://tempuri.org/cXML")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://tempuri.org/cXML", IsNullable = false)]
public partial class PunchOutSetupRequest
{

private BuyerCookie buyerCookieField;

private Extrinsic[] extrinsicField;

private BrowserFormPost browserFormPostField;

private Contact[] contactField;

private SupplierSetup supplierSetupField;

private ShipTo shipToField;

private SelectedItem selectedItemField;

private ItemOut[] itemOutField;

private PunchOutSetupRequestOperation operationField;

/// <remarks/>
public BuyerCookie BuyerCookie
{
    get
    {
        return this.buyerCookieField;
    }
    set
    {
        this.buyerCookieField = value;
    }
}

/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("Extrinsic")]
public Extrinsic[] Extrinsic
{
    get
    {
        return this.extrinsicField;
    }
    set
    {
        this.extrinsicField = value;
    }
}

/// <remarks/>
public BrowserFormPost BrowserFormPost
{
    get
    {
        return this.browserFormPostField;
    }
    set
    {
        this.browserFormPostField = value;
    }
}

/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("Contact")]
public Contact[] Contact
{
    get
    {
        return this.contactField;
    }
    set
    {
        this.contactField = value;
    }
}

/// <remarks/>
public SupplierSetup SupplierSetup
{
    get
    {
        return this.supplierSetupField;
    }
    set
    {
        this.supplierSetupField = value;
    }
}

/// <remarks/>
public ShipTo ShipTo
{
    get
    {
        return this.shipToField;
    }
    set
    {
        this.shipToField = value;
    }
}

/// <remarks/>
public SelectedItem SelectedItem
{
    get
    {
        return this.selectedItemField;
    }
    set
    {
        this.selectedItemField = value;
    }
}

/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("ItemOut")]
public ItemOut[] ItemOut
{
    get
    {
        return this.itemOutField;
    }
    set
    {
        this.itemOutField = value;
    }
}

/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public PunchOutSetupRequestOperation operation
{
    get
    {
        return this.operationField;
    }
    set
    {
        this.operationField = value;
    }
}
}

回答1:


TL;DR; I solved this by editing the xsd file prior to converting it to c# models.

In the XSD generated from the DTD, change:

<xs:schema xmlns="http://tempuri.org/cXML" xmlns:ds="uri:ds" elementFormDefault="qualified" targetNamespace="http://tempuri.org/cXML" xmlns:xs="http://www.w3.org/2001/XMLSchema">

To:

<xs:schema xmlns:ds="uri:ds" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">

Longer explanation:

If you use Visual studio's [XML]->[Create Schema] on the DTD file, visual studio will generate an XSD with target namespace http://tempuri.org/cXML.

If you generate C# models from that XSD without removing these namespace references (using xsd2code or visual studio's xsd blah.xsd /classes), then XmlSerializer will expect that namespace to be used in the XML you want to deserialize.

Platforms such as SAP Ariba do not use that tempuri.org namespace. The XML nodes will thus be skipped, because without the namespace reference the nodes are not recognized. I found that out because the XmlSerializer.UnknownNode event fired, telling me it doesn't recognize the nodes such as Header and Request, and it expects nodes with a tempuri.org namespace prefix.

So if you first remove the bogus namespace from the XSD, and then generate the classes (I used xsd2code for that), then you end up with valid c# (de)serializable models.

You then also don't need to use xRoot.ElementName = "cXML";. It will pick up the root node from the c# classes, because its not looking for a <cXML> tag with the tempuri.org namespace.

So this way you do not need to 'gut' the classes generated from XSD, and you can use them as is.



来源:https://stackoverflow.com/questions/34620074/deserializing-cxml-to-c-sharp-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!