使用c#将xsd转换为xml

本文关键字:xml 转换 xsd 使用 | 更新日期: 2023-09-27 17:50:28

如何从xsd 生成xml而不需要xsd.exe?

使用c#将xsd转换为xml

我想我谷歌了一下。从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);

问题解决了。

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