我有一个xml API,我必须模仿角色的角色。我正在尝试在.NET中使用内置的xml序列化功能,但它正在添加一些额外的属性。在NORMAL Web服务或xml API中,这些属性不会伤害任何内容,甚至可能有用。但他们是意想不到的角色,不幸的是,我不能允许他们。所以这就是我想要做的事情(当然还有假设的对象):
我有一个基本类型
public abstract class Instrument { }
...我有派生类型
public class Guitar : Instrument { }
...我想将派生类型序列化为类似的东西:
<Guitar />
相反,我明白了:
<Instrument d1p1:type="Guitar" xmlns:d1p1="http://www.w3.org/2001/XMLSchema-instance" />
以下是我正在进行的测试:
[TestClass]
public class when_serializing_a_guitar
{
private XmlSerializer _serializer;
private string _expectedXml;
private StringWriter _stringWriter;
private string _actualXml;
private XmlSerializerNamespaces _ns;
private XmlWriter _xmlWriter;
private void WithThisContext()
{
_ns = new XmlSerializerNamespaces();
_ns.Add("", "");
_stringWriter = new StringWriter();
_xmlWriter = XmlWriter.Create(_stringWriter, new XmlWriterSettings
{
OmitXmlDeclaration = true,
CloseOutput = false
});
_serializer = new XmlSerializer(typeof(Instrument), new[] { typeof(Guitar) });
_expectedXml = @"<Guitar />";
}
private void BecauseOfThisAction()
{
_serializer.Serialize(_xmlWriter, new Guitar(), _ns);
_actualXml = _stringWriter.ToString();
}
[TestMethod]
public void it_should_return_the_expected_properly_formatted_xml()
{
WithThisContext();
BecauseOfThisAction();
Assert.AreEqual(_expectedXml, _actualXml);
}
}
知道我该怎么做吗?
答案 0 :(得分:1)
我假设您需要保持域模型层次结构不变。否则你可以这样做:var serializer = new XmlSerializer(typeof(Guitar));
如果您确实需要保持原样,我建议您在每个域对象上编写自己的ToXml方法。
public interface IXmlWritable
{
string ToXml();
}
public class Instrument : IXmlWritable
{
public string classification { get; set; }
public string ToXml()
{
return "<Instrument classification='" + classification + "' />";
}
}
或者类似的东西取决于你想要如何迭代节点。
答案 1 :(得分:0)
您可以使用System.Xml.Linq中的XElement(您需要使用'add reference'添加对它的引用)。这是简单地创建干净的xml doc的代码:
XElement el = new XElement("data", new XElement("guitar"));
el.Save(@"D:\test.xml", SaveOptions.None);