繁体   English   中英

使用 C# 将 xsd 转换为 xml

[英]Convert xsd to xml using c#

如何在没有 xsd.exe 的情况下从 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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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