我正在使用c#在Visual Studio 2008中工作。
假设我有2个xsd文件,例如“Envelope.xsd”和“Body.xsd”
我通过运行xsd.exe创建了两组类,创建了类似“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来破坏所需的嵌套结果吗?
万分感谢
保
答案 0 :(得分: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 ... :)