【问题标题】:Serialize xml with equal default and named namespaces使用相同的默认命名空间和命名命名空间序列化 xml
【发布时间】:2012-10-15 12:43:35
【问题描述】:

我知道这看起来不像是最佳实践,但我需要生成具有相同命名空间的 xml

例如:

<ns1:root xsi:schemaLocation=""http://schemalocation""
xmlns:ns1=""http://schema""
xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
xmlns=""http://schema"">
...
</ns1:root>

我还向序列化程序添加了命名空间:

var xmlSerializerNamespaces = new XmlSerializerNamespaces();
xmlSerializerNamespaces.Add("ns1", "http://schema");
xmlSerializerNamespaces.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance");
xmlSerializerNamespaces.Add(string.Empty, "http://schema");

这是类本身:

[XmlRoot(ElementName = "request", Namespace = "http://schema")]
    [Serializable]
    public class Request 
    {
        [XmlAttributeAttribute("schemaLocation", Namespace = XmlSchema.InstanceNamespace)]
        public string SchemaLocation
        {
            get { return _schemaLocation; }
            set { _schemaLocation = value; }
        }

        ...

        private string _schemaLocation = "http://schemalocation";   }

所以一切都很好,但默认 xmlns 不在生成的 xml 中。 我也玩过 XmlWriterSettings 没有结果。 有没有人知道如何在不替换字符串的情况下做到这一点?)

【问题讨论】:

    标签: .net xml xml-serialization xml-namespaces


    【解决方案1】:

    默认命名空间是根据您用于添加 XML 片段的命名空间来设置的,例如

    XNamespace defaultNs = @"http://schema";
    var result = new XDocument(new XElement(defaultNs + "root"));
    

    将产生以下输出:

    <rootNode xmlns="http://schema">
    </rootNode>
    

    所以您所要做的就是将其他命名的添加到文档中,即

    XNamespace defaultNs = @"http://schema";
    var root = new XElement(defaultNs + "root",
        new XAttribute("xsi", "schemaLocation", "http://schemaLocation"),
        new XAttribute(XNamespace.Xmlns + "ns1", defaultNs"),
        new XAttribute(XNamespace.Xmlns + "xsi", "http://www.w3.org/2001/XMLSchema-instance")
    );
    

    【讨论】:

    • 谢谢,我同意这是一个解决方案,但是我需要使用从属性类到 xml 的 xmlserialization 并且使用一个对象(XDocument)并不好,尤其是当你有很大的 xml 时。你知道要避开它吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-19
    • 1970-01-01
    • 2013-06-23
    • 2010-10-07
    相关资源
    最近更新 更多