XML 使用前缀序列化元素

XML Serializing Element with prefix

<?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(命名空间?)。

有人可以创建一个简单的 class 来展示如何生成上面的 XML 吗?

为了序列化的目的,字段、属性和对象可以有一个与之关联的命名空间。您可以使用 [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>