c# - .net 类 xml 属性创建多个命名空间

标签 c# xml namespaces xml-serialization

我希望在序列化它时拥有一个类属性,以便在输出中具有多个命名空间。 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);

关于c# - .net 类 xml 属性创建多个命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7890788/

相关文章:

php - 即使在 php.ini 中安装并启用了 PDO 也未找到错误

c# - 如何确定可为空的值类型

c# - 防止服务器相同用户名中的多个实例

java - 在 netbeans 中清理和构建后从 dist 文件夹运行 jar 文件时不读取 xml 文件

android - 为什么我的搜索栏左右两侧有空格?

c++ - 在 Gaia 支持下构建音频分析库 Essentia 失败

c# - 将压缩图像与原始图像进行比较

c# - 如何在多个子类上返回不同的类型?

xml - XSLT 删除标签但保留内容

module - F#:命名空间未定义