Convert a list of objects to an xml string

inhaler picture inhaler · Jun 8, 2017 · Viewed 8.7k times · Source

Hello I have a list of object i want to convert into an xml. Here is what the final xml should look like.

<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>

I have converted each of the objects in the list into an xml string like so

//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();
}

I tried converting that list into the format above using

XElement xmlElements = new XElement("ArrayOfTweet", xmlStringTweetList.Select(i => new XElement("Tweet", i)));

But there is the extra <Tweet></Tweet> That i dont need. Is there a way of doing this?

Answer

maccettura picture maccettura · Jun 8, 2017

I made a fiddle here that illustrates a way to serialize your object all at once, instead of piecing strings together.

I suspect your extra <Tweet></Tweet> is because of a null or empty value in the list, because I am not experiencing it in my test above.