使用c#将xsd转换为xml

时间:2011-04-19 11:04:05

标签: c# xml xsd

如何在没有xsd.exe的情况下从xsd 生成xml

2 个答案:

答案 0 :(得分:12)

我想我用Google搜索了它。使用MSDN

中的XmlSampleGenerator

样品使用:

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

答案 1 :(得分:3)

问题已经解决了。

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

使用方法

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