2017-04-04 129 views
0

使用xds.exe(或other methods)從類生成XSD文件效果很好,但我無法找到將文檔(或任何類型的描述)插入到輸出XSD。從C#類代碼生成xsd註釋和文檔標記

例如,C#類

public class Animal 
{ 
    public int NumberOfLegs; 
} 

生成XSD

<?xml version="1.0" encoding="utf-16"?> 
<xs:schema elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema"> 
    <xs:element name="Animal" nillable="true" type="Animal" /> 
    <xs:complexType name="Animal"> 
    <xs:sequence> 
     <xs:element minOccurs="1" maxOccurs="1" name="NumberOfLegs" type="xs:int" /> 
    </xs:sequence> 
    </xs:complexType> 
</xs:schema> 

但是我想能夠作爲元數據添加XSD註釋到類所以XSD出來作爲

<xs:complexType name="Animal"> 
    <xs:sequence> 
    <xs:element minOccurs="1" maxOccurs="1" name="NumberOfLegs" type="xs:int"> 
     <xs:annotation> 
     <xs:documentation>Will need to be greater than 0 to walk!</xs:documentation> 
     </xs:annotation> 
    </xs:element> 
    </xs:sequence> 
</xs:complexType> 

是否有任何簡潔的方法來實現這個在C#代碼中?任何將任何類型的描述添加到xml元素/屬性的方式都可以。註釋必須與實際代碼一致,如下所示:

public class Animal 
{ 
    [XmlAnnotation("Will need to be greater than 0 to walk!")] 
    public int NumberOfLegs; 
} 

也就是說,它需要從註釋中自動記錄。

回答

0

嘗試以下操作:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Data; 
using System.Xml; 
using System.Xml.Linq; 
using System.IO; 


namespace ConsoleApplication49 
{ 

    class Program 
    { 
     const string FILENAME = @"c:\temp\test.xml"; 
     static void Main(string[] args) 
     { 
      StreamReader reader = new StreamReader(FILENAME); 
      reader.ReadLine(); //skip the xml identification with utf-16 encoding 
      XDocument doc = XDocument.Load(reader); 

      XElement firstNode = (XElement)doc.FirstNode; 
      XNamespace nsXs = firstNode.GetNamespaceOfPrefix("xs"); 

      XElement sequence = doc.Descendants(nsXs + "element").FirstOrDefault(); 

      sequence.Add(new XElement(nsXs + "annotation", 
       new XElement(nsXs + "documention", "Will need to be greater than 0 to walk!") 
       )); 

     } 
    } 


} 
+0

對不起,我的問題也許是不夠具體。評論需要與實際代碼一起,我會更新問題。 – Patrick