避免在.net DataContractSerializer中使用" http://www.w3.org/2001/XM
本文关键字:www w3 org XM 2001 http net DataContractSerializer | 更新日期: 2023-09-27 17:52:54
我有一系列的类,我正在使用。net 4.0中的。net的DataContractSerializer将它们转换为XML。序列化工作得很好,以后我可以毫无困难地解析XML并重新创建。net对象。
然而,大多数DataMember不是必需的。[DataMember(IsRequired = false)]。这在反序列化XML时非常有效,在这种情况下,您可以忽略文档中的XML节点,但是在将现有对象序列化为XML时,DataContractSerializer坚持将具有空值的属性作为带有属性(例如 )的节点写出来。[DataContract(Name = "response", Namespace = "http://domain.com/name")]
public class MyResponseClass
{
[DataMember(Name = "count", IsRequired = true, Order = 0)]
public int Count { get; set; }
[DataMember(Name = "info", IsRequired = false, Order = 1)]
public InfoClass Info { get; set; }
[DataMember(Name = "metadata", IsRequired = false, Order = 2)]
public MetadataList Metadatas { get; set; }
}
可以从
序列化<response xmlns="http://domain.com/name">
<count>4</count>
</response>
但是,如果我序列化对象,它会创建:
<response xmlns="http://domain.com/name" xmlns:i="http://www.w3.org/2001/XmlSchema-instance">
<count>4</count>
<info i:nil="true" />
<metadata i:nil="true" />
</response>
是否有任何方法可以让DataContractSerializer不写节点,而不是当它有一个空值?
使用EmitDefaultValue = false
跳过XML中的默认值:
[DataContract(Name = "response", Namespace = "http://domain.com/name")]
public class MyResponseClass
{
[DataMember(Name = "count", IsRequired = true, Order = 0, EmitDefaultValue = false)]
public int Count { get; set; }
[DataMember(Name = "info", IsRequired = false, Order = 1, EmitDefaultValue = false)]
public InfoClass Info { get; set; }
[DataMember(Name = "metadata", IsRequired = false, Order = 2, EmitDefaultValue = false)]
public MetadataList Metadatas { get; set; }
}
要删除xmlns:i="http://www.w3.org/2001/XmlSchema-instance"
,您必须使用例如Replace()
,如以下示例
public void Write(string filePath, MyResponseClass myResponse)
{
var serializer = new DataContractSerializer(typeof(MyResponseClass));
var sb = new StringBuilder();
using (var writer = new StringWriter(sb))
using (var xmlWriter = XmlWriter.Create(writer))
{
serializer.WriteObject(xmlWriter, myResponse);
}
using (StreamWriter stream = new StreamWriter(filePath))
{
sb = sb.Replace(" xmlns:i='"http://www.w3.org/2001/XMLSchema-instance'"", "");
stream.Write(sb);
}
}
with regards:)
(我在错误的问题中意外地发布了这个答案,但我认为它在这里也很有帮助,所以我现在不删除它)
[DataContract(Namespace = "")]
在每个类的顶部加上使它更好看。它删除了数据契约名称空间和难看的节点前缀。但是,标准名称空间保留了下来。这对我来说还可以。
:
<?xml version="1.0" encoding="utf-8"?>
<root xmlns:i="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://schemas.datacontract.org/2004/07/MyClassname">
<prop1>true</prop1>
<prop2 xmlns:d2p1="http://schemas.datacontract.org/2004/07/MySubclassname">
<d2p1:sub>true</d2p1:sub>
</prop2>
</root>
:后<?xml version="1.0" encoding="utf-8"?>
<root xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<prop1>true</prop1>
<prop2>
<sub>true</sub>
</prop2>
</root>