XML序列化,添加命名空间,添加声明头,添加节点前缀

xml序列化方法

/// <summary>
/// 将一个对象序列化为XML字符串
/// </summary>
/// <param name="o">要序列化的对象</param>
/// <param name="encoding">编码方式</param>
/// <returns>序列化产生的XML字符串</returns>
public static string XmlSerialize(object o, Encoding encoding)
{
    if (o == null)
        throw new ArgumentNullException("o");
    if (encoding == null)
        throw new ArgumentNullException("encoding");

    string xml = "";
    try
    {
        using (MemoryStream stream = new MemoryStream())
        {
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Encoding = encoding;

            //OmitXmlDeclaration表示不生成声明头,默认是false,OmitXmlDeclaration为true,会去掉<?xml version="1.0" encoding="UTF-8"?>
            //settings.OmitXmlDeclaration = true;

            XmlWriter writer = XmlWriter.Create(stream, settings);

            //强制指定命名空间,覆盖默认的命名空间,可以添加多个,如果要在xml节点上添加指定的前缀,可以在跟节点的类上面添加[XmlRoot(Namespace = "http://www.w3.org/2001/XMLSchema-instance", IsNullable = false)],Namespace指定哪个值,xml节点添加的前缀就是哪个命名空间(这里会添加ceb)
            XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
            namespaces.Add("ceb", "http://www.chinaport.gov.cn/ceb");
            namespaces.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance");

            XmlSerializer serializer = new XmlSerializer(o.GetType());
            serializer.Serialize(writer, o, namespaces);
            writer.Close();

            stream.Position = 0;
            using (StreamReader reader = new StreamReader(stream, encoding))
            {
                xml = reader.ReadToEnd();
            }
        }
    }
    catch (Exception ex)
    {
        
    }
    return xml;
}

对象属性:

[XmlRoot(Namespace = "http://www.chinaport.gov.cn/ceb")]
public class CEB311Message
{
    [XmlAttribute("guid")]
    public string Guid { get; set; }

    [XmlAttribute("version")]
    public string Version { get; set; }

    public Order Order { get; set; }

    public BaseTransfer BaseTransfer { get; set; }
}

public class Order
{
    public OrderHead OrderHead { get; set; }

    [XmlElement("OrderList")]
    public List<OrderList> OrderList { get; set; }
}

public class BaseTransfer
{
    public string copCode { get; set; }
    
    public string copName { get; set; }
    
    public string dxpMode { get; set; }
    
    public string dxpId { get; set; }
    
    public string note { get; set; }
}

public class OrderHead
{
    //......
}

public class OrderList
{
    //......
}

序列化以后的xml报文:

<?xml version="1.0" encoding="utf-8"?>
<ceb:CEB311Message xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" guid="F9BF2981-B2E2-4621-A15D-74E25AE6F8FD" version="1.0" xmlns:ceb="http://www.chinaport.gov.cn/ceb">
    <ceb:Order>
        <ceb:OrderHead>
            <ceb:guid>AF55F05A-1176-474A-A560-631EFAC83061</ceb:guid>
            <ceb:appType>1</ceb:appType>
            <ceb:appTime>20160708143049</ceb:appTime>
            <ceb:appStatus>2</ceb:appStatus>
            <ceb:orderType>I</ceb:orderType>
            <ceb:orderNo>XSC2016070200002</ceb:orderNo>
            <ceb:ebpCode>Alibaba888888</ceb:ebpCode>
            <ceb:ebpName>杭州阿里巴巴淘宝电子商务有限公司</ceb:ebpName>
            <ceb:ebcCode>IE123456789</ceb:ebcCode>
            <ceb:ebcName>厦门xxx软件科技有限公司</ceb:ebcName>
            <ceb:goodsValue>902.50</ceb:goodsValue>
            <ceb:freight>0</ceb:freight>
            <ceb:discount>0</ceb:discount>
            <ceb:taxTotal>90.25</ceb:taxTotal>
            <ceb:acturalPaid>902.50</ceb:acturalPaid>
            <ceb:currency>142</ceb:currency>
            <ceb:buyerRegNo>青帝</ceb:buyerRegNo>
            <ceb:buyerName>叶青</ceb:buyerName>
            <ceb:buyerIdType>1</ceb:buyerIdType>
            <ceb:buyerIdNumber>350583198909067413</ceb:buyerIdNumber>
            <ceb:payCode />
            <ceb:payName />
            <ceb:payTransactionId>ZFB20160628170422</ceb:payTransactionId>
            <ceb:batchNumbers />
            <ceb:consignee>叶青</ceb:consignee>
            <ceb:consigneeTelephone>18201010101</ceb:consigneeTelephone>
            <ceb:consigneeAddress>福建省xxx</ceb:consigneeAddress>
            <ceb:consigneeDistrict>350203</ceb:consigneeDistrict>
            <ceb:note />
        </ceb:OrderHead>
        <ceb:OrderList>
            <ceb:gnum>1</ceb:gnum>
            <ceb:itemNo>TestZS20160712242</ceb:itemNo>
            <ceb:itemName>测试海关总署商品</ceb:itemName>
            <ceb:itemDescribe />
            <ceb:barCode />
            <ceb:unit>122</ceb:unit>
            <ceb:qty>5</ceb:qty>
            <ceb:price>180.50</ceb:price>
            <ceb:totalPrice>902.50</ceb:totalPrice>
            <ceb:currency>142</ceb:currency>
            <ceb:country>304</ceb:country>
            <ceb:note />
        </ceb:OrderList>
    </ceb:Order>
    <ceb:BaseTransfer>
        <ceb:copCode>440316277F</ceb:copCode>
        <ceb:copName>xxx</ceb:copName>
        <ceb:dxpMode>DXP</ceb:dxpMode>
        <ceb:dxpId>DXPENTTEST510001</ceb:dxpId>
        <ceb:note />
    </ceb:BaseTransfer>
</ceb:CEB311Message>
CEB311Message类头上的[XmlRoot(Namespace = "http://www.chinaport.gov.cn/ceb")],Namespaces指定哪一个值,就可以添加对应命名空间的前缀
原文地址:https://www.cnblogs.com/zfylzl/p/5653432.html