我已经从XSD生成了这样的类型:
```xml
输出结果如下:
为什么根元素没有设置命名空间?当然,我可以像这样强制设置它:
那么输出就是这样的:
```xml
我已经从XSD生成了这样的类型:
```[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>
但我觉得我不应该需要额外的步骤。反序列化时,也需要类似的代码。这个属性有问题吗?还是说这就是事情的运作方式,需要额外的步骤呢?