[Solved] How to convert List to xml document in c#


You may use XElement or XDocument and LINQ. Providing a sample of what the XML should look like we could provide more info.

For instance:

BugWSResponseList1.Add("<Bug><family>TEST22</family><product>Dr.Watson</product><version>Xpress API</version><productarea>1</productarea><subarea></subarea><qe>sdawar</qe><duplicateId></duplicateId></Bug>");

BugWSResponseList1.Add("<Bug><family>ESG</family><product>Dr.Watson</product><version>Xpress API</version><productarea>1</productarea><subarea></subarea><qe>sdawar</qe><duplicateId></duplicateId></Bug>");

XElement xe = new XElement
              (
                  "Bugs",
                  BugWSResponseList1
                  .Select 
                  (
                      x=>
                      XElement.Parse(x)
                  )
              );

So after i have loaded the list with the two pieces of xml you have provided i do the following:

I create a new XElement that will hold the root of the XML. I name that root as Bugs. Then as children of that root i put the contents of your List after parsing them into XElement objects.

The above code will result to :

<Bugs>
  <Bug>
    <family>TEST22</family>
    <product>Dr.Watson</product>
    <version>Xpress API</version>
    <productarea>1</productarea>
    <subarea></subarea>
    <qe>sdawar</qe>
    <duplicateId></duplicateId>
  </Bug>
  <Bug>
    <family>ESG</family>
    <product>Dr.Watson</product>
    <version>Xpress API</version>
    <productarea>1</productarea>
    <subarea></subarea>
    <qe>sdawar</qe>
    <duplicateId></duplicateId>
  </Bug>
</Bugs>

What you were missing was the root element. XmlDocument needs to have a root element defined.

In your case you could get away with it in you code by just adding in the start of your joined string and in the end, like the following, but i think my solution is more robust.

XmlDocument xd = new XmlDocument();
string s = "<Bugs>" + string.Join(",", BugWSResponseList2) + "</Bugs>";                    
xd.LoadXml(s);

4

solved How to convert List to xml document in c#