【问题标题】:Custom C# XML/XSD from a classes来自类的自定义 C# XML/XSD
【发布时间】:2014-04-28 17:38:01
【问题描述】:

我正在尝试从我定义的类中获取 xml。这是我的课

public class MyClass
{
    public string Name { get; set; }        
    public MyAttribute[] Elements { get; set; }
}

public class MyAttribute
{
    public string Name { get; set; }
    public object Value { get; set; }
    public string Type { get; private set; }
}


MyClass myClass = new MyClass();
myClass.Name = "Class1";
myClass.Elements = new MyAttribute[3] {
    new MyAttribute(){ Name = "Att1", Value = 4 },
    new MyAttribute(){ Name = "Att2", Value = 5 },
    new MyAttribute(){ Name = "Att3", Value = 6 }
}; 

我想要这个 xml

<?xml version="1.0" encoding="utf-8" ?>
<Class1>
  <Att1>4</Att1>
  <Att2>5</Att2>
  <Att3>6</Att3>
</Class1>

可以生成这个xml和他的xsd。谢谢。

编辑: 我使用 XmlDocument 类(System.Xml)解决了这样的问题:

public class MyClass
{
    public string Name { get; set; }
    public MyAttribute[] Elements { get; set; }

    public XmlDocument Xml()
    {
        XmlDocument xmlDoc = new XmlDocument();
        XmlNode rootNode = xmlDoc.CreateElement(this.Name);
        foreach (MyAttribute att in this.Elements)
        {
            XmlElement xmlElement = xmlDoc.CreateElement(att.Name);
            xmlElement.InnerText = att.Value.ToString();
            rootNode.AppendChild(xmlElement);
        }
        xmlDoc.AppendChild(rootNode);
        return xmlDoc;
    }
}

对于 XSD,我使用的是 XmlSchema (System.Xml.Schema)

【问题讨论】:

  • 数据库在哪里?

标签: c# xml xsd


【解决方案1】:

我不确定您的描述中的数据库在哪里,但是为了从您的类的实例创建 XML 文件,您可以使用 XmlElementXmlAttribute 属性来装饰类,然后按照描述对其进行序列化here.

为了创建XSD,您可以尝试使用here建议的XSD工具。

编辑

其实看 XML 你想得到,你甚至不必使用属性,只需使用XmlSerializer 类,如链接之一所述。例如,要将生成的 XML 保存为字符串,可以使用:

// before calling this code, create an instance of MyClass and fill properties with appropriate values
// let's assume the instance is named instanceOfMyClass

var stringBuilder = new StringBuilder();
using (TextWriter writer = new StringWriter(stringBuilder))
{
    var serializer = new System.Xml.Serialization.XmlSerializer(typeof(MyClass));
    serializer.Serialize(writer, instanceOfMyClass);
}

//now You can call stringBuilder.ToString() to get string with the serialized XML

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-06
    • 2015-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多