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>
不過,這並不正確坐我,我必須做的額外步驟。反序列化時,需要類似的代碼。這個屬性有什麼問題嗎?還是僅僅是事物的工作方式,以及是否需要執行額外的步驟?