2017-04-04 83 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