[英]deserializing an xml to c# object and serializing it in a different way
嗨,我有一個Web服務,它使用以下XML來為我的應用程序供稿:
<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>
基本上與輸入XML相同,除了嵌入標簽setProdotti,流和流內,它們是固定的且已知的(可以硬編碼)。 可以用當前模型完成嗎? 我嘗試使用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>
謝謝你的幫助。
根據Alexander Petrov的建議,我詳細研究了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
的部分避免了在Value元素(p)上創建XML屬性,並且我設置了XmlWriterSetting
以便在字符串的開頭沒有XML聲明。 顯然.Dispose()
關閉了我用.WriteStartElement
打開的標簽。 我一直在尋找.Close()
方法,但是它不再存在。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.