XML序列化和命名空间prefixes [英] XML Serialization and namespace prefixes

查看:143
本文介绍了XML序列化和命名空间prefixes的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在寻找用C#的方式,我可以序列化类转换成XML,并添加一个命名空间,但是它定义该命名空间将使用preFIX。

I'm looking for a way with C# which I can serialize a class into XML and add a namespace, but define the prefix which that namespace will use.

最后我想生成以下XML:

Ultimately I'm trying to generate the following XML:

<myNamespace:Node xmlns:myNamespace="...">
  <childNode>something in here</childNode>
</myNamespace:Node>

我知道有两个的DataContractSerializer 的XmlSerializer 我可以添加一个命名空间,但他们似乎产生内部preFIX,与我不能够控制的东西。我是否能与这两种序列化来控制它(我可以使用他们的)?

I know with both the DataContractSerializer and the XmlSerializer I can add a namespace, but they seem to generate a prefix internally, with something that I'm not able to control. Am I able to control it with either of these serializers (I can use either of them)?

如果我无法控制我需要写我自己的XML序列化的命名空间的产生,如果是这样,什么是最好的之一,它写的?

If I'm not able to control the generation of the namespaces will I need to write my own XML serializer, and if so, what's the best one to write it for?

推荐答案

要控制命名空间别名,使用 XmlSerializerNamespaces

To control the namespace alias, use XmlSerializerNamespaces.

[XmlRoot("Node", Namespace="http://flibble")]
public class MyType {
    [XmlElement("childNode")]
    public string Value { get; set; }
}

static class Program
{
    static void Main()
    {
        XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
        ns.Add("myNamespace", "http://flibble");
        XmlSerializer xser = new XmlSerializer(typeof(MyType));
        xser.Serialize(Console.Out, new MyType(), ns);
    }
}

如果您需要更改的命名的在运行时,您还可以使用 XmlAttributeOverrides

If you need to change the namespace at runtime, you can additionally use XmlAttributeOverrides.

这篇关于XML序列化和命名空间prefixes的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆