简体   繁体   English

.net类xml属性用于创建多个名称空间

[英].net class xml attribute to create multiple namespaces

I want to have a class property when serializing it to have multiple namespaces in the output. 我想在序列化它时在输出中有多个名称空间时有一个类属性。 The XmlElementAttribute isn't working for me. XmlElementAttribute对我不起作用。 Can anyone help? 有人可以帮忙吗?

My code: 我的代码:

XML Output: XML输出:

<MyClass>
    <Property1 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"/>
    <Property2/>
</MyClass>

Class: 类:

public class MyClass
{
    [XmlElementAttribute(Namespace = "http://www.w3.org/2001/XMLSchema-instance")]
    public string Property1 { get; set; }

    public string Property1 { get; set; }
}

The serializer can defines prefixes (like in your example) but you only have one namespace per element. 序列化程序可以定义前缀(如示例中所示),但每个元素只有一个名称空间。 Use XmlElementAttribute (aka XmlElement) for the single relevant namespace and define prefixes when you serialize. 对单个相关命名空间使用XmlElementAttribute(aka XmlElement)并在序列化时定义前缀。

To get this: 要得到这个:

<?xml version="1.0" encoding="utf-16"?>
<OrderedItem xmlns:inventory="http://www.cpandl.com" xmlns:money="http://www.cohowinery.com">
    <inventory:ItemName>Widget</inventory:ItemName>
    <inventory:Description>Regular Widget</inventory:Description>
    <money:UnitPrice>2.3</money:UnitPrice>
    <inventory:Quantity>10</inventory:Quantity>
    <money:LineTotal>23</money:LineTotal>
</OrderedItem>

You have: 你有:

public class OrderedItem
{
    [XmlElementAttribute(Namespace = "http://www.cpandl.com")]
    public string ItemName { get; set; }
    [XmlElementAttribute(Namespace = "http://www.cpandl.com")]
    public string Description { get; set; }
    [XmlElementAttribute(Namespace = "http://www.cohowinery.com")]
    public decimal UnitPrice { get; set; }
    [XmlElementAttribute(Namespace = "http://www.cpandl.com")]
    public int Quantity { get; set; }
    [XmlElementAttribute(Namespace = "http://www.cohowinery.com")]
    public int LineTotal { get; set; }
}

And serialize with prefixes set in your XmlSerializerNamespaces: 并使用XmlSerializerNamespaces中设置的前缀进行序列化:

OrderedItem example = new OrderedItem
            {
                ItemName = "Widget",
                Description = "Regular Widget",
                UnitPrice = (decimal) 2.3,
                Quantity = 10,
                LineTotal = 23
            };

XmlSerializer serializerX = new XmlSerializer(example.GetType());
XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
namespaces.Add("inventory", "http://www.cpandl.com");
namespaces.Add("money", "http://www.cohowinery.com");
serializerX.Serialize(Console.Out, example, namespaces);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM