2011-01-05 4 views
8

때 코드와 객체 직렬화 :XML 직렬화 된 출력에 XML 스키마에 대한 참조를 추가

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

출력 XML 파일에서 내가 얻을 :

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

가 어떻게에 대한 참조를 추가하려면

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

답변

12

[편집]

: 그것에 XML 스키마는, 그래서 다음과 같습니다

IXmlSerializable을 명시 적으로 구현하고 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); 

가장 이상적인 해결책은 아니지만 다음 필드와 특성을 클래스에 추가하면 트릭을 수행 할 수 있습니다.

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

또 다른 옵션으로는 사용자 지정 XmlTextWriter 클래스를 만들 수 있습니다.

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

또는 직렬화

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(...); 

희망이 도움이 ... 세부 사항에 대한

+0

감사를 사용하지 마십시오. 굉장한 대답! –

+0

여기서'XmlSchema.Namespace'와'XmlSchema.InstanceNamespace' 상수를 사용할 수 있습니다. – tm1