你好,我有一个对象列表,想要将它们转换为XML格式。以下是最终XML的样式:
<ArrayOfTweet>
<Tweet>
<Photos>
<Photo>
<PhotoHeight>FOO</PhotoHeight>
<PhotoUri>a/random/ur/path</PhotoUri>
<PhotoWidth>923</PhotoWidth>
<SourcePhotoUri>a/random/path</SourcePhotoUri>
</Photo>
</Photos>
<ProfileImage>a/random/path</ProfileImage>
<ScreenName>FOO</ScreenName>
<Text>some text</Text>
<TweetId>1234</TweetId>
<UserId>1234</UserId>
<Username>BAR</Username>
</Tweet>
<Tweet>
<Photos>
<Photo>
<PhotoHeight>FOO</PhotoHeight>
<PhotoUri>a/random/ur/path</PhotoUri>
<PhotoWidth>923</PhotoWidth>
<SourcePhotoUri>a/random/path</SourcePhotoUri>
</Photo>
</Photos>
<ProfileImage>a/random/path</ProfileImage>
<ScreenName>FOO</ScreenName>
<Text>some text</Text>
<TweetId>1234</TweetId>
<UserId>1234</UserId>
<Username>BAR</Username>
</Tweet>
</ArrayOfTweet>
我已将列表中的每个对象转换为XML字符串,如下所示。
//TweetList is the list of tweet objects
List<string> xmlStringTweetList = new List<string>();
foreach (var tl in TweetList)
{
xmlStringTweetList.Add(toXML(tl));
}
private string toXML(Tweet t)
{
var stringwriter = new System.IO.StringWriter();
var serializer = new XmlSerializer(t.GetType());
serializer.Serialize(stringwriter, t);
return stringwriter.ToString();
}
我尝试使用以下方式将该列表转换为上述格式:
XElement xmlElements = new XElement("ArrayOfTweet", xmlStringTweetList.Select(i => new XElement("Tweet", i)));
但是有一个额外的<Tweet></Tweet>
,我不需要。有没有办法解决这个问题?