反序列化XML到C#对象,并以不同的方式
问题描述:
您好我有一个用下面的XML提要我的应用程序的Web服务其序列:反序列化XML到C#对象,并以不同的方式
<Value><TABLE>
<PRODUCT>
<ProductID> 1 </ProductID>
<Category> sport </Category>
<Description> calcio </Description>
<Name> palla </Name>
<Price> 10 </Price>
</PRODUCT>
<PRODUCT>
<ProductID> 2 </ProductID>
<Category> sport </Category>
<Description> tennis </Description>
<Name> racchetta </Name>
<Price> 100 </Price>
</PRODUCT>
<PRODUCT>
<ProductID> 3 </ProductID>
<Category> sport </Category>
<Description> golf </Description>
<Name> borsa </Name>
<Price> 150 </Price>
</PRODUCT>
</TABLE></Value>
我写了下面的对象模型和我设法正确地将反序列化使用XmlSerializer。现在
[XmlRoot("Value")]
public class Value {
[XmlElement("TABLE")]
public TABLE TABLE { get; set; }
}
public class TABLE {
[XmlElement("PRODUCT")]
public List<Product> Products { get; set; }
}
public class Product {
public int ProductID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Category { get; set; }
public int Price { get; set; }
}
,我最终添加新的产品对象,我想序列化模型到和XML,以将其发送回Web服务。问题是,接受XML结构略低不同,我想的XML结构是这样的:
<setProdotti>
<streams>
<instream>
<Value><TABLE>
<PRODUCT>
<ProductID> 1 </ProductID>
<Category> sport </Category>
<Description> calcio </Description>
<Name> palla </Name>
<Price> 10 </Price>
</PRODUCT>
</TABLE></Value>
</instream>
</streams>
</setProdotti>
基本上相同,与嵌入标签setProdotti,溪流和河道内的异常的输入XML ,这是固定的和已知的(可以硬编码)。 它可以用当前模型完成吗?我尝试使用XmlSerializer的Serialize方法,但id输出基于模型的XML(当然)以及我想避免的根元素上的标记。
<?xml version="1.0" encoding="utf-16"?><Value xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<TABLE>
<PRODUCT><ProductID>1</ProductID><Name> palla </Name><Description> nike </Description><Category> calcio </Category><Price>10</Price></PRODUCT>
</TABLE>
</Value>
感谢您的帮助。
答
继亚历山大·彼得罗夫的建议,我看着详细的XmlWriter 产生的代码满足我的要求是:
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
XmlSerializer xmlserializer = new XmlSerializer(typeof(Value));
StringWriter stringWriter = new StringWriter();
XmlWriter writer2 = XmlWriter.Create(stringWriter, new XmlWriterSettings {
OmitXmlDeclaration = true,
ConformanceLevel = ConformanceLevel.Fragment
});
writer2.WriteStartElement("setProdotti");
writer2.WriteStartElement("streams");
writer2.WriteStartElement("instream");
xmlserializer.Serialize(writer2, p, ns);
writer2.Dispose();
string serializedXml = stringWriter.ToString();
约XmlSerializerNamespaces
的部分避免XML的创造价值元素的属性(P ),并且我设置了XmlWriterSetting
,以便在字符串的开头没有XML声明。 显然.Dispose()
关闭我用.WriteStartElement
打开的标签。我正在寻找.Close()
方法,但它不再存在。
最简单的解决方案是使用必要的元素名称返回嵌套在三个容器类中的'Value'对象。有没有理由不能这样做? – dbc
您可以使用'XmlWriter'手动在xml周围创建三个元素。 –