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