为什么 XmlTypeAttribute.Namespace 不能为根元素设置命名空间?

3
我已经从XSD生成了这样的类型:
```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>

但我觉得我不应该需要额外的步骤。反序列化时,也需要类似的代码。这个属性有问题吗?还是说这就是事情的运作方式,需要额外的步骤呢?

1个回答

7

[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"/>

这个怎么能够在svcutil生成的类中实现呢? - zaitsman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接