【发布时间】:2017-10-30 01:25:19
【问题描述】:
您好,我有一个向我的应用程序提供以下 XML 的 Web 服务:
<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; }
}
现在,我最终添加了新的 Product 对象,并且我想将模型序列化为 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、streams 和 instream 之外,与输入 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>
感谢您的帮助。
【问题讨论】:
-
最简单的解决方案是返回嵌套在三个具有必要元素名称的容器类中的
Value对象。你有什么理由不能这样做吗? -
您可以使用
XmlWriter在 xml 周围手动创建三个元素。
标签: c# .net xml serialization