我正在尝试像这样生成XML:
<?xml version="1.0"?> <!DOCTYPE APIRequest SYSTEM "https://url"> <APIRequest> <Head> <Key>123</Key> </Head> <ObjectClass> <Field>Value</Field </ObjectClass> </APIRequest>
我有一个类(ObjectClass)用XMLSerialization属性装饰,如下所示:
[XmlRoot("ObjectClass")] public class ObjectClass { [XmlElement("Field")] public string Field { get; set; } }
而我真正的黑客直观的想法,只是得到这个工作是做这个,当我序列化:
ObjectClass inst = new ObjectClass(); XmlSerializer serializer = new XmlSerializer(inst.GetType(),""); StringWriter w = new StringWriter(); w.WriteLine(@"<?xml version=""1.0""?>"); w.WriteLine("<!DOCTYPE APIRequest SYSTEM"); w.WriteLine(@"""https://url"">"); w.WriteLine("<APIRequest>"); w.WriteLine("<Head>"); w.WriteLine(@"<Field>Value</Field>"); w.WriteLine(@"</Head>"); XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add("",""); serializer.Serialize(w,inst,ns); w.WriteLine("</APIRequest>");
但是,这样生成XML:
<?xml version="1.0"?> <!DOCTYPE APIRequest SYSTEM "https://url"> <APIRequest> <Head> <Key>123</Key> </Head> <?xml version="1.0" encoding="utf-16"?> <ObjectClass> <Field>Value</Field> </ObjectClass> </APIRequest>
即serialize语句自动添加<?xml文本声明。 我知道我正在攻击这个错误,有人可以指出我正确的方向吗? 作为一个注释,我认为只要在其中添加一个ObjectClass就可以实现APIRequest类(因为有20种不同类型的ObjectClass,每个类都需要这个样板),但是如果我是错误。
不要使用字符串连接构建xml。这是邪恶的
输出:
<?xml version="1.0" encoding="utf-16"?> <!DOCTYPE APIRequest SYSTEM "https://url"> <APIRequest> <Head> <Key>123</Key> </Head> <ObjectClass> <Field>Value</Field> </ObjectClass> </APIRequest>
码:
using System; using System.Diagnostics; using System.Text; using System.Xml; using System.Xml.Serialization; public static class Program { public static void Main() { var obj = new ObjectClass { Field = "Value" }; var settings = new XmlWriterSettings { Indent = true }; var xml = new StringBuilder(); using (var writer = XmlWriter.Create(xml,settings)) { Debug.Assert(writer != null); writer.WriteDocType("APIRequest",null,"https://url",null); writer.WriteStartElement("APIRequest"); writer.WriteStartElement("Head"); writer.WriteElementString("Key","123"); writer.WriteEndElement(); // </Head> var nsSerializer = new XmlSerializerNamespaces(); nsSerializer.Add("",""); var xmlSerializer = new XmlSerializer(obj.GetType(),""); xmlSerializer.Serialize(writer,obj,nsSerializer); writer.WriteEndElement(); // </APIRequest> } Console.WriteLine(xml.ToString()); Console.ReadLine(); } } [XmlRoot("ObjectClass")] public class ObjectClass { [XmlElement("Field")] public string Field { get; set; } }