1

I am serialising an object to XML and I get the output like so :

<?xml version="1.0" encoding="utf-8"?>
<SOrd xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">

However I would like it to be like so :

<SOrd xmlns:SOrd="http://..." xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://....xsd">

How can I do this?

I have tried adding attributes to the root object before serialisation and also this :

XmlSerializerNamespaces xmlNameSpace = new XmlSerializerNamespaces();
xmlNameSpace.Add("xmlns:SOrd", "http://...");
xmlNameSpace.Add("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
xmlNameSpace.Add("xsi:schemaLocation", "http://....xsd");

XmlSerializer xs = new XmlSerializer(ord.GetType());
TextWriter writer = new StreamWriter(outputPath, false);
xs.Serialize(writer, ord, xmlNameSpace);
writer.Close();

But I get the exception "The ':' character, hexadecimal value 0x3A, cannot be included in a name."

sprocket12
  • 5,368
  • 18
  • 64
  • 133

1 Answers1

2

the prefic can't contain the ":", take out the first part xmlns:

here is your code slighly changed:

XmlSerializerNamespaces xmlNameSpace = new XmlSerializerNamespaces();
xmlNameSpace.Add("SOrd", "http://...");
xmlNameSpace.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance");
xmlNameSpace.Add("schemaLocation", "http://....xsd");

XmlSerializer xs = new XmlSerializer(ord.GetType());
TextWriter writer = new StreamWriter(outputPath, false);
xs.Serialize(writer, ord, xmlNameSpace);
writer.Close();

make sure to add the required attributes for each class since the serialization attributes are not inhereted. for more about the inheretence of attributes check: How to deserialize concrete implementation of abstract class from XML

EDIT

you can achieve the xsi:shcemaLocation Like that:

 [XmlRoot(ElementName = "FooData", Namespace = "http://foo.bar", DataType = "schemaLocation")]  
  public class Foo
  {
    [System.Xml.Serialization.XmlAttributeAttribute(AttributeName = "schemaLocation", Namespace = "http://www.w3.org/2001/XMLSchema-instance")]
    public string schemaLocation = "http://example";
  }
Community
  • 1
  • 1
Swift
  • 1,861
  • 14
  • 17
  • I just did this before I read your message and it works, but the schemaLocation needs to have a prefix of xsi: how do I acheieve this? – sprocket12 Jul 23 '13 at 10:52
  • Thanks it works :) one last thing is it possible to order the schema defs in a certail way? They seem to mixed around when output – sprocket12 Jul 23 '13 at 11:17
  • I don't think it is possible, or at least I don't know of such a way. exept if you create your document using XmlWriter. – Swift Jul 23 '13 at 11:28