XmlSerializer:删除不必要的xsi和xsd命名空间

时间:2009-04-17 12:44:22

标签: .net xml xml-serialization

有没有办法配置XmlSerializer,以便它不会在根元素中写入默认名称空间?

我得到的是:

<?xml ...>
<rootelement xmlns:xsi="..." xmlns:xsd="...">
</rootelement>

我想删除两个xmlns声明。

重复How to serialize an object to XML without getting xmlns=”…”?

5 个答案:

答案 0 :(得分:244)

//Create our own namespaces for the output
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();

//Add an empty namespace and empty value
ns.Add("", "");

//Create the serializer
XmlSerializer slz = new XmlSerializer(someType);

//Serialize the object with our own namespaces (notice the overload)
slz.Serialize(myXmlTextWriter, someObject, ns)

答案 1 :(得分:56)

由于Dave要求我重复我对Omitting all xsi and xsd namespaces when serializing an object in .NET的回答,我已经更新了这篇文章,并在上述链接中重复了我的回答。此答案中使用的示例与用于其他问题的示例相同。以下内容是逐字复制的。


在线阅读了Microsoft的文档和几个解决方案之后,我发现了解决这个问题的方法。它通过XmlSerializer与内置IXmlSerialiazble和自定义XML序列化一起使用。

要使用,我将使用迄今为止在此问题的答案中使用的相同MyTypeWithNamespaces XML样本。

[XmlRoot("MyTypeWithNamespaces", Namespace="urn:Abracadabra", IsNullable=false)]
public class MyTypeWithNamespaces
{
    // As noted below, per Microsoft's documentation, if the class exposes a public
    // member of type XmlSerializerNamespaces decorated with the 
    // XmlNamespacesDeclarationAttribute, then the XmlSerializer will utilize those
    // namespaces during serialization.
    public MyTypeWithNamespaces( )
    {
        this._namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] {
            // Don't do this!! Microsoft's documentation explicitly says it's not supported.
            // It doesn't throw any exceptions, but in my testing, it didn't always work.

            // new XmlQualifiedName(string.Empty, string.Empty),  // And don't do this:
            // new XmlQualifiedName("", "")

            // DO THIS:
            new XmlQualifiedName(string.Empty, "urn:Abracadabra") // Default Namespace
            // Add any other namespaces, with prefixes, here.
        });
    }

    // If you have other constructors, make sure to call the default constructor.
    public MyTypeWithNamespaces(string label, int epoch) : this( )
    {
        this._label = label;
        this._epoch = epoch;
    }

    // An element with a declared namespace different than the namespace
    // of the enclosing type.
    [XmlElement(Namespace="urn:Whoohoo")]
    public string Label
    {
        get { return this._label; }
        set { this._label = value; }
    }
    private string _label;

    // An element whose tag will be the same name as the property name.
    // Also, this element will inherit the namespace of the enclosing type.
    public int Epoch
    {
        get { return this._epoch; }
        set { this._epoch = value; }
    }
    private int _epoch;

    // Per Microsoft's documentation, you can add some public member that
    // returns a XmlSerializerNamespaces object. They use a public field,
    // but that's sloppy. So I'll use a private backed-field with a public
    // getter property. Also, per the documentation, for this to work with
    // the XmlSerializer, decorate it with the XmlNamespaceDeclarations
    // attribute.
    [XmlNamespaceDeclarations]
    public XmlSerializerNamespaces Namespaces
    {
        get { return this._namespaces; }
    }
    private XmlSerializerNamespaces _namespaces;
}

这就是全班。现在,有些人反对在他们班级的某个地方有一个XmlSerializerNamespaces对象;但正如你所看到的,我把它整齐地隐藏在默认构造函数中并公开了一个公共属性来返回命名空间。

现在,当需要序列化类时,您将使用以下代码:

MyTypeWithNamespaces myType = new MyTypeWithNamespaces("myLabel", 42);

/******
   OK, I just figured I could do this to make the code shorter, so I commented out the
   below and replaced it with what follows:

// You have to use this constructor in order for the root element to have the right namespaces.
// If you need to do custom serialization of inner objects, you can use a shortened constructor.
XmlSerializer xs = new XmlSerializer(typeof(MyTypeWithNamespaces), new XmlAttributeOverrides(),
    new Type[]{}, new XmlRootAttribute("MyTypeWithNamespaces"), "urn:Abracadabra");

******/
XmlSerializer xs = new XmlSerializer(typeof(MyTypeWithNamespaces),
    new XmlRootAttribute("MyTypeWithNamespaces") { Namespace="urn:Abracadabra" });

// I'll use a MemoryStream as my backing store.
MemoryStream ms = new MemoryStream();

// This is extra! If you want to change the settings for the XmlSerializer, you have to create
// a separate XmlWriterSettings object and use the XmlTextWriter.Create(...) factory method.
// So, in this case, I want to omit the XML declaration.
XmlWriterSettings xws = new XmlWriterSettings();
xws.OmitXmlDeclaration = true;
xws.Encoding = Encoding.UTF8; // This is probably the default
// You could use the XmlWriterSetting to set indenting and new line options, but the
// XmlTextWriter class has a much easier method to accomplish that.

// The factory method returns a XmlWriter, not a XmlTextWriter, so cast it.
XmlTextWriter xtw = (XmlTextWriter)XmlTextWriter.Create(ms, xws);
// Then we can set our indenting options (this is, of course, optional).
xtw.Formatting = Formatting.Indented;

// Now serialize our object.
xs.Serialize(xtw, myType, myType.Namespaces);

完成此操作后,您应该获得以下输出:

<MyTypeWithNamespaces>
    <Label xmlns="urn:Whoohoo">myLabel</Label>
    <Epoch>42</Epoch>
</MyTypeWithNamespaces>

我已经在最近的一个项目中成功使用了这个方法,这个项目具有深层次的类,这些类被序列化为XML以进行Web服务调用。微软的文档不是很清楚,一旦你创建了它,可以对公众可访问的XmlSerializerNamespaces成员做些什么,而且很多人认为它没用。但是通过遵循他们的文档并以上面显示的方式使用它,您可以自定义XmlSerializer如何为您的类生成XML,而无需诉诸于不支持的行为或者#34;滚动您自己的&#34;通过实施IXmlSerializable进行序列化。

我希望这个答案能够一劳永逸地解决如何摆脱xsi生成的标准xsdXmlSerializer命名空间。

更新:我只是想确保回答OP有关删除所有命名空间的问题。我上面的代码适用于此;让我来告诉你怎么做。现在,在上面的示例中,您实际上无法摆脱所有名称空间(因为有两个名称空间正在使用中)。在XML文档的某处,您需要拥有xmlns="urn:Abracadabra" xmlns:w="urn:Whoohoo之类的内容。如果示例中的类是较大文档的一部分,则必须为AbracadbraWhoohoo中的任何一个(或两者)声明命名空间上方的某个位置。如果没有,那么一个或两个命名空间中的元素必须用某种类型的前缀进行修饰(你不能有两个默认的命名空间,对吧?)。因此,对于此示例,Abracadabra是默认命名空间。我可以在MyTypeWithNamespaces类中为Whoohoo命名空间添加名称空间前缀,如下所示:

public MyTypeWithNamespaces
{
    this._namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] {
        new XmlQualifiedName(string.Empty, "urn:Abracadabra"), // Default Namespace
        new XmlQualifiedName("w", "urn:Whoohoo")
    });
}

现在,在我的班级定义中,我指出<Label/>元素位于命名空间"urn:Whoohoo"中,因此我不需要做任何进一步的操作。当我现在使用上面的序列化代码序列化类时,这是输出:

<MyTypeWithNamespaces xmlns:w="urn:Whoohoo">
    <w:Label>myLabel</w:Label>
    <Epoch>42</Epoch>
</MyTypeWithNamespaces>

因为<Label>与文档的其余部分位于不同的名称空间中,所以它必须在某种程度上被装饰&#34;使用命名空间。请注意,仍然没有xsixsd名称空间。


这结束了我对另一个问题的回答。但我想确保我回答OP关于不使用名称空间的问题,因为我觉得我还没有真正解决它。假设<Label>是与文档其余部分相同的命名空间的一部分,在本例中为urn:Abracadabra

<MyTypeWithNamespaces>
    <Label>myLabel<Label>
    <Epoch>42</Epoch>
</MyTypeWithNamespaces>

你的构造函数看起来就像在我的第一个代码示例中一样,以及用于检索默认命名空间的公共属性:

// As noted below, per Microsoft's documentation, if the class exposes a public
// member of type XmlSerializerNamespaces decorated with the 
// XmlNamespacesDeclarationAttribute, then the XmlSerializer will utilize those
// namespaces during serialization.
public MyTypeWithNamespaces( )
{
    this._namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] {
        new XmlQualifiedName(string.Empty, "urn:Abracadabra") // Default Namespace
    });
}

[XmlNamespaceDeclarations]
public XmlSerializerNamespaces Namespaces
{
    get { return this._namespaces; }
}
private XmlSerializerNamespaces _namespaces;

然后,稍后,在使用MyTypeWithNamespaces对象进行序列化的代码中,您可以像上面那样调用它:

MyTypeWithNamespaces myType = new MyTypeWithNamespaces("myLabel", 42);

XmlSerializer xs = new XmlSerializer(typeof(MyTypeWithNamespaces),
    new XmlRootAttribute("MyTypeWithNamespaces") { Namespace="urn:Abracadabra" });

...

// Above, you'd setup your XmlTextWriter.

// Now serialize our object.
xs.Serialize(xtw, myType, myType.Namespaces);

XmlSerializer将吐出与上面显示的相同的XML,输出中没有其他名称空间:

<MyTypeWithNamespaces>
    <Label>myLabel<Label>
    <Epoch>42</Epoch>
</MyTypeWithNamespaces>

答案 2 :(得分:6)

还有另一种选择 - 您可以在要序列化的类型中提供类型XmlSerializerNamespaces的成员。用XmlNamespaceDeclarations属性装饰它。将名称空间前缀和URI添加到该成员。然后,任何未明确提供XmlSerializerNamespaces的序列化都将使用您放入类型中的名称空间前缀+ URI对。

示例代码,假设这是您的类型:

[XmlRoot(Namespace = "urn:mycompany.2009")]
public class Person {
  [XmlAttribute] 
  public bool Known;
  [XmlElement]
  public string Name;
  [XmlNamespaceDeclarations]
  public XmlSerializerNamespaces xmlns;
}

你可以这样做:

var p = new Person
  { 
      Name = "Charley",
      Known = false, 
      xmlns = new XmlSerializerNamespaces()
  }
p.xmlns.Add("",""); // default namespace is emoty
p.xmlns.Add("c", "urn:mycompany.2009");

这意味着该实例的任何序列化都没有指定其自己的前缀+ URI对的集合,将使用“urn:mycompany.2009”命名空间的“p”前缀。它还将省略xsi和xsd命名空间。

这里的区别在于您将XmlSerializerNamespaces添加到类型本身,而不是在调用XmlSerializer.Serialize()时显式使用它。这意味着如果您的类型的实例是由您不拥有的代码序列化的(例如在Web服务堆栈中),并且该代码未显式提供XmlSerializerNamespaces,则该序列化程序将使用实例中提供的命名空间。

答案 3 :(得分:0)

我正在使用:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        const string DEFAULT_NAMESPACE = "http://www.something.org/schema";
        var serializer = new XmlSerializer(typeof(Person), DEFAULT_NAMESPACE);
        var namespaces = new XmlSerializerNamespaces();
        namespaces.Add("", DEFAULT_NAMESPACE);

        using (var stream = new MemoryStream())
        {
            var someone = new Person
            {
                FirstName = "Donald",
                LastName = "Duck"
            };
            serializer.Serialize(stream, someone, namespaces);
            stream.Position = 0;
            using (var reader = new StreamReader(stream))
            {
                Console.WriteLine(reader.ReadToEnd());
            }
        }
    }
}

要获取以下XML:

<?xml version="1.0"?>
<Person xmlns="http://www.something.org/schema">
  <FirstName>Donald</FirstName>
  <LastName>Duck</LastName>
</Person>

如果您不想要名称空间,只需将DEFAULT_NAMESPACE设置为“”。

答案 4 :(得分:0)

我知道它很脏,但它对我有用,只是使用正则表达式来摆脱垃圾。我只是不想要任何 xmlns 的东西,想像对待普通的 JSON 一样对待 XML。其他回答太有仪式感了。

所以在序列化对象后,我这样做:

string xml = "<string xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">Hello, world!</string>";
xml = Regex.Replace(x, @" xmlns:.*?"".*?""", "");