0

我正在使用 c# 在 Visual Studio 2008 中工作。

假设我有 2 个 xsd 文件,例如“Envelope.xsd”和“Body.xsd”

我通过运行 xsd.exe 创建了 2 组类,创建了“Envelope.cs”和“Body.cs”之类的东西,到目前为止一切都很好。

我不知道如何将两个类链接到序列化(使用 XmlSerializer)到正确的嵌套 xml 中,即:

我想: <Envelope><DocumentTitle>Title</DocumentTitle><Body>Body Info</Body></Envelope>

但我得到: <Envelope><DocumentTitle>Title</DocumentTitle></Envelope><Body>Body Info</Body>

有人可以告诉我这两个 .cs 类应该如何使 XmlSerializer 能够运行所需的嵌套结果吗?

太感谢了

保罗

4

1 回答 1

0

这应该这样做(示例控制台程序):

using System;
using System.IO;
using System.Text;
using System.Xml.Serialization;

namespace ConsoleApplication9
{
    [XmlRoot("Envelope")]
    public class EnvelopeClass
    {
        [XmlElement("DocumentTitle")]
        public string DocumentTitle { get; set; }

        [XmlElement("Body")]
        public BodyClass BodyElement { get; set; }
    }

    public class BodyClass
    {
        [XmlText()]
        public string Body { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            EnvelopeClass envelope =
                new EnvelopeClass
                {
                    DocumentTitle = "Title",
                    BodyElement = new BodyClass { Body = "Body Info" }
                };

            XmlSerializer xs = new XmlSerializer(typeof(EnvelopeClass));

            StringBuilder sb = new StringBuilder();
            StringWriter writer = new StringWriter(sb);
            xs.Serialize(writer, envelope);
            Console.WriteLine(sb.ToString());
            Console.ReadLine();
        }
    }
}

结果输出:

    <?xml version="1.0" encoding="utf-16"?>
    <Envelope 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      <DocumentTitle>Title</DocumentTitle>
      <Body>Body Info</Body>
    </Envelope>

希望有帮助!记得标记我的帖子已回答pleez ... :)

于 2010-04-15T17:43:33.663 回答