0

I have a simple method that is used C# .Net classes to serialize a list of objects to a XML string. For that method, I'd like to remove xml elements from the produced XML string. Please help. Thank you.

My method:

  public static string CreateXML(List<Video> list)
        {
            string result = "";
            StringWriter stringWriter = new StringWriter();
            XmlSerializer s = new XmlSerializer(list.GetType());
            s.Serialize(stringWriter, list);

            result = stringWriter.ToString();

            return result;
        }

The result string (I cut off for brevity) I get from that method:

 <?xml version="1.0" encoding="utf-16" ?> 
 <ArrayOfVideo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">

    <Video>- 
         ....
     </Video>

     <Video>
       ....
     </Video>

  </ArrayOfVideo>

I would like to have a result xml string like: (tag is added <Videos> and </Videos>)

<Videos>
    <Video>- 
             ....
         </Video>

         <Video>
           ....
         </Video>
</Videos>

So, I want to remove lines:

<?xml version="1.0" encoding="utf-16" ?> 
<ArrayOfVideo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
</ArrayOfVideo>
1
  • See if this SO post helps. Commented Nov 26, 2014 at 19:14

1 Answer 1

0

You can use LINQ to XML to parse easily the document and create a new XElement with name "Videos" having the "Video" elements inside from the loaded and parsed document. This can be done in two lines with LINQ to XML.

XElement element1 = XElement.Load("Videos.xml");

XElement element2 = new XElement ("Videos", element1.Elements("Video"));
Sign up to request clarification or add additional context in comments.

2 Comments

@Efstahios, thank for you answer. But my method needs to have List<Video> list collection to be passed in as argument instead reading an external xml file.
Possible duplicate question. Go here: stackoverflow.com/questions/1772004/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.