xmlserializernamespaces将命名空间添加到特定元素

时间:2014-01-27 14:12:05

标签: c# xml-serialization xmlserializer

我有一个对象,我想序列化它。我想将命名空间添加到xml文档的特定元素。我从1个默认的xml创建了几个.xsd文件。我使用XmlSerializer。

应在<sos:element中描述名称空间。这就是我想要的:

<env:root
  xmls:env ="httpenv"
  xmlns:sos="httpsos">
   <env:body>
     <sos:element 
       xmlns:abc="" <--------------my namespaces are located in <sos:element
       ...

如果我使用

之类的东西
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("abc", "httpabc");
ns.add....
StringWriter stringWriter = new StringWriter();   
serializer.Serialize(stringWriter, ObjectToSerialize, ns);

我会得到以下

<env:root
  xmls:env ="httpenv"
  xmlns:sos="httpsos"
  xmlns:abc="" <-------------I do not want it here; I want it in <sos:element
   <env:body>
     <sos:element> 
      ...

有没有办法指定我希望声明命名空间的位置(在哪个元素中),或者它们是否都在根元素中声明了?

1 个答案:

答案 0 :(得分:1)

从XML的角度来看,XML命名空间的定义并不重要。如果您需要在特定位置使用XML命名空间声明,则解析XML的组件可能有问题。

嗯,无论如何,这就是我想出来的:

using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace XMLNamespaceChangeSerialization
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var serialize = Serialize();
            Console.WriteLine(serialize);
            Console.ReadLine();
        }

        private static string Serialize()
        {
            var ns = new XmlSerializerNamespaces();
            ns.Add("env", "httpenv");
            // Don't add it here, otherwise it will be defined at the root element
            // ns.Add("sos", "httpsos");
            var stringWriter = new StringWriter();
            var serializer = new XmlSerializer(typeof (RootClass), "httpenv");
            serializer.Serialize(stringWriter, new RootClass(), ns);
            return stringWriter.ToString();
        }
    }


    [Serializable]
    [XmlRoot(ElementName = "root")]
    public class RootClass
    {
        [XmlElement(ElementName = "body", Namespace = "httpenv")]
        public BodyClass body = new BodyClass();
    }

    [Serializable]
    public class BodyClass
    {
        [XmlElement( ElementName = "element", Namespace = "httpsos")]
        public SOSClass element = new SOSClass();
    }

    [Serializable]
    public class SOSClass
    {
        // This will be used by XML serializer to determine the namespaces
        [XmlNamespaceDeclarations]
        public XmlSerializerNamespaces xmlns = new XmlSerializerNamespaces(
                    new[] { new XmlQualifiedName("sos", "httpsos"), });
    }
}