2015-01-08 52 views
2

我已经产生了从XSD文件看起来像这样类型:为什么XmlTypeAttribute.Namespace没有为根元素设置一个名称空间?

[XmlType(Namespace = "http://example.com")] 
public class Foo 
{ 
    public string Bar { get; set; } 
} 

当序列是这样的:

var stream = new MemoryStream(); 
new XmlSerializer(typeof(Foo)).Serialize(stream, new Foo() { Bar = "hello" }); 
var xml = Encoding.UTF8.GetString(stream.ToArray()); 

输出是这样的:

<?xml version="1.0"?> 
<Foo xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
    <Bar xmlns="http://example.com">hello</Bar> 
</Foo> 

为什么根元素不有命名空间设置?当然,我可以迫使它这样的:

var stream = new MemoryStream(); 
var defaultNamespace = ((XmlTypeAttribute)Attribute.GetCustomAttribute(typeof(Foo), typeof(XmlTypeAttribute))).Namespace; 
new XmlSerializer(typeof(Foo), defaultNamespace).Serialize(stream, new Foo() { Bar = "hello" }); 
var xml = Encoding.UTF8.GetString(stream.ToArray()); 

那么输出是这样的:

<?xml version="1.0"?> 
<Foo xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns="http://example.com"> 
    <Bar>hello</Bar> 
</Foo> 

不过,这并不正确坐我,我必须做的额外步骤。反序列化时,需要类似的代码。这个属性有什么问题吗?还是仅仅是事物的工作方式,以及是否需要执行额外的步骤?

回答

4

[XmlType]既不设置根元素的名称也不设置名称空间。它设置它所在类的类型

要设置根元素的名称,请使用[XmlRoot]

[XmlRoot(Name="FooElement", Namespace = "http://example.com")] // NS for root element 
[XmlType(Name="FooType", Namespace = "http://example.com/foo")] // NS for the type itself 
public class Foo 
{ 
    public string Bar { get; set; } 
} 

的名称和命名空间由[XmlType]设置将在XML模式中可以看出你的序列化类型,可能在complexType声明。如果需要,也可以在xsi:type属性中看到。


上述声明将生成XML

<ns1:FooElement xmlns:ns1="http://example.com"> 

与XSD

<xsd:element name="FooElement" type="ns2:FooType" xmlns:ns2="http://example.com/foo"/> 
相关问题