Domanda

I have an object and I would like to serialize it. I would like to add the namespaces to a specific element of the xml document. I have created several .xsd files from 1 default xml. I use XmlSerializer.

The namespace should be described in the <sos:element. That is what I want:

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

if I use something like

XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("abc", "httpabc");
ns.add....
StringWriter stringWriter = new StringWriter();   
serializer.Serialize(stringWriter, ObjectToSerialize, ns);

I will get the following

<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> 
      ...

Is there a way to specify where (in which element) I would like to have my namespaces declared or are they all declared in the root element?

È stato utile?

Soluzione

From XML perspective, it doesn't matter where the XML namespace is defined. If you need the XML namespace declaration at a particular place, there's probably something wrong with the component that parses the XML.

Well, anyway, this is what I came up with:

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"), });
    }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top