将对象列表转换为XML字符串

4

你好,我有一个对象列表,想要将它们转换为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>,我不需要。有没有办法解决这个问题?


为什么不采用整个对象结构并一次性序列化所有内容呢? - maccettura
你的意思是序列化TweetList对象吗?我尝试过了,但是我无法弄清楚如何使其正常工作。我一直在收到错误。你有什么建议吗?如果可以这样做,我会很高兴的,因为这样会更容易。 - inhaler
我刚刚发布了一个答案,说明如何将它序列化为一个对象。 - maccettura
方括号中的类型是错误的。请删除Tweet上面的[XmlArray]并替换为[XmlElement]。 - jdweng
2个回答

5

我在这里制作了一个fiddle(链接),演示了一种将对象整体序列化的方法,而不是拼接字符串。

我怀疑你多出来的<Tweet></Tweet>是由于列表中存在空值或空列表引起的,因为在我的上面的测试中没有遇到这个问题。


1
我认为XElement xmlElements = new XElement("ArrayOfTweet", xmlStringTweetList.Select(i => XElement.Parse(i)));就可以了。

谢谢@Martin,我遇到了一个错误:System.Xml.XmlElement不包含“Parse”的定义,但是我在这里检查https://msdn.microsoft.com/en-us/library/bb468714(v=vs.110).aspx,它确实存在。我需要找出为什么会出现这种情况。 - inhaler
抱歉,应该是 XElement.Parse - Martin Honnen
谢谢Martin,我已经做出了更改,它也起作用了!但是我会选择@maccetturas的小提琴,因为它更干净。 - inhaler

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接