简体   繁体   English

使用XmlSerializer添加没有前缀的命名空间

[英]Use XmlSerializer to add a namespace without a prefix

I want my output to look like this 我希望我的输出看起来像这样

<OrderContainer xmlns="http://blabla/api/products" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">

So I added the following to my XmlSerializer 所以我将以下内容添加到我的XmlSerializer中

XmlSerializer x = new XmlSerializer(typeof(OrderContainer));
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "http://blabla/api/products");
ns.Add("i", "http://www.w3.org/2001/XMLSchema-instance");
// do stuff..
x.Serialize(stream, orderContainer, ns);

But now I get 但现在我明白了

<OrderContainer xmlns:i="http://www.w3.org/2001/XMLSchema-instance">

So how do I edit the default namespace? 那么我该如何编辑默认命名空间呢?


My object definition is like: 我的对象定义如下:

[System.Runtime.Serialization.DataContractAttribute(Name="OrderContainer", Namespace="http://blabla/api/products")]
[System.SerializableAttribute()]
public partial class OrderContainer

You could use the XmlSerializer constructor which takes a default namespace in addition to the type you want to serialize: 除了要序列化的类型之外,您还可以使用XmlSerializer构造函数该构造函数采用默认名称空间:

var x = new XmlSerializer(
    typeof(OrderContainer), 
    "http://blabla/api/products");
var ns = new XmlSerializerNamespaces();
ns.Add("i", "http://www.w3.org/2001/XMLSchema-instance");
x.Serialize(stream, orderContainer, ns);

如果要使用XML Serializer,则必须使用[XmlElementAttribute] ,而不是[DataContractAttribute]

Ah, had to use DataContractSerializer , which automatically generates correct XML, including the namespaces. 啊,必须使用DataContractSerializer ,它自动生成正确的XML,包括命名空间。

DataContractSerializer dcs = new DataContractSerializer(typeof(OrderContainer));
//do stuff..
dcs.WriteObject(s, orderContainer);

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

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