use*_*702 3 c# xml xml-serialization
我从XSD生成了类似的类型:
[XmlType(Namespace = "http://example.com")]
public class Foo
{
public string Bar { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
如下序列化:
var stream = new MemoryStream();
new XmlSerializer(typeof(Foo)).Serialize(stream, new Foo() { Bar = "hello" });
var xml = Encoding.UTF8.GetString(stream.ToArray());
Run Code Online (Sandbox Code Playgroud)
输出是这样的:
<?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>
Run Code Online (Sandbox Code Playgroud)
为什么根元素没有设置名称空间?当然,我可以这样强迫它:
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());
Run Code Online (Sandbox Code Playgroud)
然后输出是这样的:
<?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>
Run Code Online (Sandbox Code Playgroud)
但我不得不做我必须做的额外步骤.反序列化时,需要类似的代码.该属性是否有问题,或者说事情是如何工作的,是否有望进行额外的步骤?
[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; }
}
Run Code Online (Sandbox Code Playgroud)
设置的名称和名称空间[XmlType]
将在XML Schema中显示为序列化类型,可能在complexType
声明中.xsi:type
如果需要,也可以在属性中看到它.
上述声明将生成XML
<ns1:FooElement xmlns:ns1="http://example.com">
Run Code Online (Sandbox Code Playgroud)
使用XSD
<xsd:element name="FooElement" type="ns2:FooType" xmlns:ns2="http://example.com/foo"/>
Run Code Online (Sandbox Code Playgroud)