我定义了以下类:
public class Root
{
public string Name;
public string XmlString;
}
并创建了一个对象:
Root t = new Root
{ Name = "Test",
XmlString = "<Foo>bar</Foo>"
};
当我使用XmlSerializer类来序列化这个对象时,它将返回xml:
<Root>
<Name>Test</Name>
<XmlString><Foo>bar</Foo></XmlString>
</Root>
如何让它不编码我的XmlString内容,以便我可以将序列化的xml作为
<XmlString><Foo>bar</Foo></XmlString>
谢谢, 伊恩
答案 0 :(得分:13)
您可以将自定义序列化限制为仅需要特别注意的元素。
public class Root
{
public string Name;
[XmlIgnore]
public string XmlString
{
get
{
if (SerializedXmlString == null)
return "";
return SerializedXmlString.Value;
}
set
{
if (SerializedXmlString == null)
SerializedXmlString = new RawString();
SerializedXmlString.Value = value;
}
}
[XmlElement("XmlString")]
[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
public RawString SerializedXmlString;
}
public class RawString : IXmlSerializable
{
public string Value { get; set; }
public XmlSchema GetSchema()
{
return null;
}
public void ReadXml(System.Xml.XmlReader reader)
{
this.Value = reader.ReadInnerXml();
}
public void WriteXml(System.Xml.XmlWriter writer)
{
writer.WriteRaw(this.Value);
}
}
答案 1 :(得分:2)
你可以(ab)使用IXmlSerializable interface和XmlWriter.WriteRaw。但正如garethm指出的那样,你几乎必须编写自己的序列化代码。
using System;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
namespace ConsoleApplicationCSharp
{
public class Root : IXmlSerializable
{
public string Name;
public string XmlString;
public Root() { }
public void WriteXml(System.Xml.XmlWriter writer)
{
writer.WriteElementString("Name", Name);
writer.WriteStartElement("XmlString");
writer.WriteRaw(XmlString);
writer.WriteFullEndElement();
}
public void ReadXml(System.Xml.XmlReader reader) { /* ... */ }
public XmlSchema GetSchema() { return (null); }
public static void Main(string[] args)
{
Root t = new Root
{
Name = "Test",
XmlString = "<Foo>bar</Foo>"
};
System.Xml.Serialization.XmlSerializer x = new XmlSerializer(typeof(Root));
x.Serialize(Console.Out, t);
return;
}
}
}
打印
<?xml version="1.0" encoding="ibm850"?>
<Root>
<Name>Test</Name>
<XmlString><Foo>bar</Foo></XmlString>
</Root>
答案 2 :(得分:1)
试试这个:
public class Root
{
public string Name;
public XDocument XmlString;
}
Root t = new Root
{ Name = "Test",
XmlString = XDocument.Parse("<Foo>bar</Foo>")
};
答案 3 :(得分:0)
我希望您需要为此案例编写自己的序列化,或者使其成为XmlString字段是包含foo字段的结构。