简体   繁体   中英

Custom C# XML/XSD from a classes

i am trying to get a xml from classes that i defined. This are my classes

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 }
}; 

i would like get this xml

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

is possible generate this xml and his xsd. thanks.

EDIT : I solved using XmlDocument class (System.Xml) like this:

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;
    }
}

For XSD, I'm using XmlSchema (System.Xml.Schema)

I'm not sure where is the database in Your description, but in order to create XML file from instances of Your classes, You can use XmlElement and XmlAttribute attributes to decorate the classes and then serialize it as described here .

In order to create XSD, you can try to use XSD tool as suggested here .

Edit

In fact, looking at XML You want to get, You even don't have to use the attributes, just use XmlSerializer class as described in one of the links. For example, to save the generated XML to a string, You can use:

// 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM