带有前缀的XML序列化元素

时间:2015-02-09 17:32:03

标签: c# xml xml-serialization

<?xml version="1.0" encoding="UTF-8"?>
<rs:model-request xsi:schemaLocation="http://www.ca.com/spectrum/restful/schema/request ../../../xsd/Request.xsd " xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:rs="http://www.ca.com/spectrum/restful/schema/request" throttlesize="100">
<rs:target-models>

我无法理解C#XmlSerializer。我已经成功地序列化了没有前缀的元素,例如rs:*。我也无法找到如何添加xsi:,xmlns:xsi和xmlns:rs(名称空间?)。

是否有人能够创建一个简单的类来展示如何生成上述XML?

1 个答案:

答案 0 :(得分:2)

字段,属性和对象可以具有与其关联的命名空间以用于序列化目的。您可以使用[XmlRoot(...)],[XmlElement(...)]和[XmlAttribute(...)]等属性指定名称空间:

[XmlRoot(ElementName = "MyRoot", Namespace = MyElement.ElementNamespace)]
public class MyElement
{
    public const string ElementNamespace = "http://www.mynamespace.com";
    public const string SchemaInstanceNamespace = "http://www.w3.org/2001/XMLSchema-instance";

    [XmlAttribute("schemaLocation", Namespace = SchemaInstanceNamespace)]
    public string SchemaLocation = "http://www.mynamespace.com/schema.xsd";

    public string Content { get; set; }
}

然后使用XmlSerializerNamespaces对象在序列化期间关联所需的名称空间前缀:

var obj = new MyElement() { Content = "testing" };
var namespaces = new XmlSerializerNamespaces();
namespaces.Add("xsi", MyElement.SchemaInstanceNamespace);
namespaces.Add("myns", MyElement.ElementNamespace);
var serializer = new XmlSerializer(typeof(MyElement));
using (var writer = File.CreateText("serialized.xml"))
{
    serializer.Serialize(writer, obj, namespaces);
}

最终输出文件如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<myns:MyRoot xmlns:myns="http://www.mynamespace.com" xsi:schemaLocation="http://www.mynamespace.com/schema.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <myns:Content>testing</myns:Content>
</myns:MyRoot>