繁体   English   中英

基于xsd模式生成xml(使用.NET)

[英]generating xml based on xsd schema (with .NET)

我想根据我的xsd架构(cap.xsd)生成一个xml文件。 我找到了这篇文章,并按照说明操作: 使用XSD文件生成XML文件

  • 我已经在xsd.exe的帮助下创建了这个类,并通过拖放到我的解决方案中插入它
  • 之后,我构建了我的解决方案并创建了xml。 但它不基于xsd架构。
  • xml文件有一个包含字符的元素,但架构说必须有数字(双)

  • 无论如何,我没有看到xsd架构对生成的xml有什么影响? 如果我删除了架构,则仍会创建xml文件。 并且在此行创建了xml文件:

    var data = new Program {Time =“abc”,Source =“443543253243”,};

..而不是我的架构:

怎么了?


我的课:

namespace testapp
{
    using System.IO;
    using System.Xml.Serialization;

    public class Program
    {
        public string Time;
        public string Source;

        public static void Main()
        {
            var data = new Program
                {
                    Time = "abc",
                    Source = "buffalo",
                };

            var serializer = new XmlSerializer(typeof(Program));
            using (var stream = new StreamWriter("E:\\cap_test.xml"))
            {
                serializer.Serialize(stream, data);
            }
        }
    }
}

我的架构:

<?xml version="1.0"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <xsd:element name="cap" type="capType"/>
    <xsd:complexType name="capType">
        <xsd:sequence>
            <xsd:element name="tel" type="telType" minOccurs="0" maxOccurs="unbounded"/>
        </xsd:sequence>
    </xsd:complexType>
    <xsd:complexType name="telType">
        <xsd:sequence>
            <xsd:element name="time" type="xsd:double"/>
            <xsd:element name="source" type="xsd:string"/>
        </xsd:sequence>
    </xsd:complexType>
</xsd:schema>

和我的xml文件:

<?xml version="1.0" encoding="utf-8"?>
<Program xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <Time>abc</Time>
    <Source>buffalo</Source>
</Program>

您应该使用从xsd生成的类,而不是使用Program 我跑的时候

xsd /classes schema.xsd

它创建一个schema.cs文件。 当我在我的项目中包含它时,我可以编写这段代码:

class Program
{
    public static void Main()
    {
        var data = new capType { tel = new[] {
           new telType { source = "buffalo", time = 1 }
        } };

        var serializer = new XmlSerializer(typeof(capType));
        using (var stream = new StreamWriter(@"E:\cap_test.xml"))
        {
            serializer.Serialize(stream, data);
        }
    }
}

写道:

<?xml version="1.0" encoding="utf-8"?>
<cap xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <tel>
    <time>1</time>
    <source>buffalo</source>
  </tel>
</cap>

schema.cs time属性为double类型的事实意味着您只能输入有效数字。

暂无
暂无

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

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