Convert xsd to xml using c #

How can I create xml from xsd without xsd.exe ?

+5
source share
2 answers

I think I was looking for him for you. Use XmlSampleGeneratorfrom MSDN

Using an example:

XmlTextWriter textWriter = new XmlTextWriter("po.xml", null);
textWriter.Formatting    = Formatting.Indented;
XmlQualifiedName qname   = new XmlQualifiedName("PurchaseOrder",       
                           "http://tempuri.org");
XmlSampleGenerator generator = new XmlSampleGenerator("po.xsd", qname);
genr.WriteXml(textWriter);
+12
source

The problem is resolved.

private void CreateXML(XmlNode xsdNode, XmlElement element, ref XmlDocument xml)
    {
        if (xsdNode.HasChildNodes)
        {
            var childs = xsdNode.ChildNodes;
            foreach (XmlNode node in childs)
            {
                XmlElement newElement = null;
                if (node.Name == "xs:element")
                {
                    newElement = xml.CreateElement(node.Attributes["name"].Value);
                    CreateXML(node, newElement, ref xml);
                    if (element == null)
                        xml.AppendChild(newElement);
                    else
                        element.AppendChild(newElement);
                }
                if (node.Name == "xs:attribute")
                {
                    element.SetAttribute(node.Attributes["name"].Value, "");
                }
                if ((node.Name == "xs:complexType") || (node.Name == "xs:sequence") || (node.Name == "xs:schema"))
                    CreateXML(node, element, ref xml);
            }
        }
    }

How to use

XmlDocument xsd = new XmlDocument();
xsd.Load(xsdFileName);
XmlNode xsdNode = xsd.DocumentElement;
XmlElement element = null;
XmlDocument xml = new XmlDocument();
CreateXML(xsdNode, element, ref xml);
+3
source

All Articles