2015-01-08 49 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"/> 
相關問題