List的 XML 序列化 - XML 根
关于 Stackoverflow (.Net 2.0) 的第一个问题:
所以我尝试返回一个列表的 XML,其中包含以下内容:
public XmlDocument GetEntityXml()
{
StringWriter stringWriter = new StringWriter();
XmlDocument xmlDoc = new XmlDocument();
XmlTextWriter xmlWriter = new XmlTextWriter(stringWriter);
XmlSerializer serializer = new XmlSerializer(typeof(List<T>));
List<T> parameters = GetAll();
serializer.Serialize(xmlWriter, parameters);
string xmlResult = stringWriter.ToString();
xmlDoc.LoadXml(xmlResult);
return xmlDoc;
}
现在这将用于我已经定义的多个实体。
假设我想获取 List
的 XML,
该 XML 类似于:
<ArrayOfCat>
<Cat>
<Name>Tom</Name>
<Age>2</Age>
</Cat>
<Cat>
<Name>Bob</Name>
<Age>3</Age>
</Cat>
</ArrayOfCat>
在获取这些实体时,有没有办法让我始终获得相同的根?
示例:
<Entity>
<Cat>
<Name>Tom</Name>
<Age>2</Age>
</Cat>
<Cat>
<Name>Bob</Name>
<Age>3</Age>
</Cat>
</Entity>
另请注意,我不打算将 XML 反序列化回 List
First question on Stackoverflow (.Net 2.0):
So I am trying to return an XML of a List with the following:
public XmlDocument GetEntityXml()
{
StringWriter stringWriter = new StringWriter();
XmlDocument xmlDoc = new XmlDocument();
XmlTextWriter xmlWriter = new XmlTextWriter(stringWriter);
XmlSerializer serializer = new XmlSerializer(typeof(List<T>));
List<T> parameters = GetAll();
serializer.Serialize(xmlWriter, parameters);
string xmlResult = stringWriter.ToString();
xmlDoc.LoadXml(xmlResult);
return xmlDoc;
}
Now this will be used for multiple Entities I have already defined.
Say I would like to get an XML of List<Cat>
The XML would be something like:
<ArrayOfCat>
<Cat>
<Name>Tom</Name>
<Age>2</Age>
</Cat>
<Cat>
<Name>Bob</Name>
<Age>3</Age>
</Cat>
</ArrayOfCat>
Is there a way for me to get the same Root all the time when getting these Entities?
Example:
<Entity>
<Cat>
<Name>Tom</Name>
<Age>2</Age>
</Cat>
<Cat>
<Name>Bob</Name>
<Age>3</Age>
</Cat>
</Entity>
Also note that I do not intend to Deserialize the XML back to List<Cat>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
有一个非常简单的方法:
There is a much easy way:
如果我理解正确,您希望文档的根始终相同,无论集合中元素的类型是什么? 在这种情况下,您可以使用 XmlAttributeOverrides :
If I understand correctly, you want the root of the document to always be the same, whatever the type of element in the collection ? In that case you can use XmlAttributeOverrides :
实现同一件事的更好方法:
A better way to the same thing:
很简单....
so simple....