.net类XML属性来创建多个名称空间
本文关键字:空间 创建 XML 属性 net | 更新日期: 2023-09-27 18:12:26
我希望在序列化它时拥有一个类属性,以便在输出中具有多个名称空间。XmlElementAttribute不适合我。有人能帮忙吗?
<标题>我的代码:XML输出:
<MyClass>
<Property1 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"/>
<Property2/>
</MyClass>
类:public class MyClass
{
[XmlElementAttribute(Namespace = "http://www.w3.org/2001/XMLSchema-instance")]
public string Property1 { get; set; }
public string Property1 { get; set; }
}
标题>
序列化器可以定义前缀(就像在您的示例中一样),但是每个元素只有一个名称空间。对单个相关的命名空间使用XmlElementAttribute(又名XmlElement),并在序列化时定义前缀。
获取:
<?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>
你有:
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; }
}
并使用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);