XmlSerialization:使用属性和值序列化为Xml Class字段

时间:2019-03-03 21:19:04

标签: c# xmlserializer

我需要以指定格式发送到其他公司的Web服务Xml。

他们无法提供util来自动创建类的XSD,因此我描述了所有使用过的类并尝试使用XmlSerializer。

示例为必填格式(数百种类型之一):

<?xml version="1.0" encoding="utf-8"?>
<PurchasePlan>
    <Guid description="Guid" type="string">72F0543E-B95A-4E5F-9F96-F8126F16C107</Guid>
    <CreateDate description="Date and time of creation" type="DateTime">2018-12-20T10:10:15.000Z</CreateDate>
    <RegistrationNumber description="RegistrationNumber of purchase plan" type="string"/>
    <Name description="Purchase plan name" type="string">Purchase no.8 according to 223 Federal Law</Name>
    <Status>
        <Name description="Status name" type="string">Approved</Name>
        <Code description="Status code" type="int">1</Code>
    </Status>
....
....
</PurchasePlan>

Xml中的每个节点可以包含值(类型:int,字符串,guid,其他类)和属性(描述,类型,EntityName)

我正在尝试制作通用类Etprf_Element,它将使用属性和值进行序列化

public class Etprf_Element
{
    [XmlAttribute]
    public string description { get; set; }
    [XmlAttribute]
    public string type { get; set; }
    [XmlAttribute]
    public string EntityName { get; set; }
    [XmlElement]
    public object Value { get; set; }
}

这是用于生成PurchasePlan.Xml的类

[XmlRootAttribute("PurchasePlan", Namespace = "http://www.cpandl.com", IsNullable = true)]
public class Etprf_PurchasePlan
{  
    [XmlElement]
    public Etprf_Element Guid = new Etprf_Element() {description = "Guid", type = "string" };    
    public Etprf_Element CreateDate = new Etprf_Element() { description = "Date and time of creation", type = "DateTime" };    
    public Etprf_Element RegistrationNumber = new Etprf_Element() { description = "RegistrationNumber of purchase plan", type = "string" }    
    public Etprf_Element Name = new Etprf_Element<String>() { description = "Purchase plan name", type = "string" };
....
}

使用类和填充值:

Etprf_PurchasePlan oEtprf_PurchasePlan = new Etprf_PurchasePlan();

oEtprf_PurchasePlan.Guid.Value = Guid.NewGuid().ToString(); // FieldValue = Guid.NewGuid().ToString();            
oEtprf_PurchasePlan.CreateDate.Value = GetPlanCreateDateTime().Date.ToString();
oEtprf_PurchasePlan.RegistrationNumber.Value = "";
oEtprf_PurchasePlan.Name.Value = GetPlanName();
...

所以,我得到

<?xml version="1.0" encoding="utf-8"?>
<PurchasePlan xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.cpandl.com">
    <Guid description="Guid" type="string">
        <Value>a24cf959-4944-452d-8eb9-2a8a8513a616</Value>
    </Guid>
    <CreateDate description="Date and time of creation" type="DateTime">
        <Value>2018-12-20T10:10:15.000Z</Value>
    </CreateDate>
    <RegistrationNumber description="RegistrationNumber of purchase plan" type="string">
        <Value/>
    </RegistrationNumber>

如果我将类描述为基本类型

public class PurchasePlan
{
Guid Guid
DateTime CreateDate
string RegistrationNumber
...
...
}

它将完美地序列化而没有属性。 但是我需要它们。

0 个答案:

没有答案