【问题标题】:XML Serializing Element with prefix带前缀的 XML 序列化元素
【发布时间】:2015-02-09 17:32:02
【问题描述】:
<?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 吗?

【问题讨论】:

    标签: c# xml xml-serialization


    【解决方案1】:

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

    【讨论】:

    • 我试过这很好,当你想给根添加一个前缀但我想给根下的其他节点添加一个前缀。它已被添加到下一个节点
    猜你喜欢
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-25
    • 1970-01-01
    • 2011-01-21
    相关资源
    最近更新 更多