2011-01-05 16 views
8

Podczas szeregowania obiektu z kodem:Dodając odwołanie do schematu XML XML Output szeregowane

var xmlSerializer = new XmlSerializer(typeof(MyType)); 
using (var xmlWriter = new StreamWriter(outputFileName)) 
{ 
    xmlSerializer.Serialize(xmlWriter, myTypeInstance); 
} 

w pliku wyjściowym xml uzyskać:

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

Jak mogę dodać odwołanie do XML schema do niego, więc wygląda to tak:

<MyType xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
     xsi:noNamespaceSchemaLocation="mySchema.xsd"> 

Odpowiedz

12

[Edytuj]

Można zaimplementować jawnie IXmlSerializable i samodzielnie napisać/przeczytać xml.

public class MyType : IXmlSerializable 
{ 
    void IXmlSerializable.WriteXml(XmlWriter writer) 
    { 
     writer.WriteAttributeString("xmlns:xsd", "http://www.w3.org/2001/XMLSchema"); 
     writer.WriteAttributeString("xsi", "noNamespaceSchemaLocation", XmlSchema.InstanceNamespace, "mySchema.xsd"); 

     // other elements & attributes 
    } 

    XmlSchema IXmlSerializable.GetSchema() 
    { 
     throw new NotImplementedException(); 
    } 

    void IXmlSerializable.ReadXml(XmlReader reader) 
    { 
     throw new NotImplementedException(); 
    } 
} 

xmlSerializer.Serialize(xmlWriter, myTypeInstance); 

Najprawdopodobniej nie jest idealnym rozwiązaniem, ale dodając następujące pola i atrybut klasy rade.

public class MyType 
{ 
    [XmlAttribute(AttributeName="noNamespaceSchemaLocation", Namespace="http://www.w3.org/2001/XMLSchema-instance")] 
    public string Schema = @"mySchema.xsd"; 
} 

Inną opcją jest utworzenie własnej niestandardowej klasy XmlTextWriter.

xmlSerializer.Serialize(new CustomXmlTextWriter(xmlWriter), myTypeInstance); 

Albo nie używać serializacji

var xmlDoc = new XmlDocument(); 
xmlDoc.AppendChild(xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null)); 

var xmlNode = xmlDoc.CreateElement("MyType"); 
xmlDoc.AppendChild(xmlNode); 

xmlNode.SetAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); 
xmlNode.SetAttribute("xmlns:xsd", "http://www.w3.org/2001/XMLSchema"); 

var schema = xmlDoc.CreateAttribute("xsi", "noNamespaceSchemaLocation", "http://www.w3.org/2001/XMLSchema-instance"); 
schema.Value = "mySchema.xsd"; 
xmlNode.SetAttributeNode(schema); 

xmlDoc.Save(...); 

nadzieję, że to pomaga ...

+0

Dzięki za szczegóły. Niesamowita odpowiedź! –

+0

Należy zauważyć, że można tutaj użyć stałych 'XmlSchema.Namespace' i' XmlSchema.InstanceNamespace'. – tm1