Search code examples
c#xmlxmldocument

Creating xml document from a list<string> in c#


I have a list "fetchXmlList" of strings which contains different fetch xmls. I want to create xml document using this list.

Xml document looks like:

<mappings>
 <main_fetchxml>
    fetchXmlList[0]
 </main_fetchxml>
 <relatedqueries>
    fetchXmlList[1]
    fetchXmlList[2]
         .
         .
         .
 </relatedqueries>
</mappings>

For relatedqueries xml node, I will have to add foreach loop and iterate over each list items starting from 2nd list item till the end of the list.

I started writing following lines of code:

 XmlDocument fetchXmlDoc = new XmlDocument();
 XmlElement rootNode = fetchXmlDoc.CreateElement("main_fetchxml");
 fetchXmlDoc.AppendChild(rootNode);
 rootNode.AppendChild(fetchXmlList[0]);

But appending list item to XmlElement object doesn't allow. Is there any other way?

Any help will be appreciated. Thanks in advance.


Solution

  • 1) you must have a root element

    2) try this code

    public static string Fetch2Xml(string s)
    {      
        return HttpUtility.HtmlDecode(s);
    }
    
    private static void Main(string[] args)
    {
        String s = "&lt;fetch distinct=\"false\" no-lock=\"false\" mapping=\"logical\" /&gt;";
    
        String[] sa = new string[] { s, s, s, s, s, s, s };
    
        XmlDocument doc = new XmlDocument();
    
        XmlElement someRoot = doc.CreateElement("mappings");
    
        XmlElement ele = doc.CreateElement("main_fetchxml");
        ele.InnerXml = Fetch2Xml(sa[0]);
        someRoot.AppendChild(ele);
    
        XmlElement ele2 = doc.CreateElement("relatedqueries");
    
        for (int a = 1; a < sa.Length; ++a)
        {
            ele2.InnerXml += Fetch2Xml(sa[a]);
        }
    
        someRoot.AppendChild(ele2);
        doc.AppendChild(someRoot);
    
        doc.Save(@"c:\temp\bla.xml");
    }
    

    that will lead too :

    <mappings>
      <main_fetchxml>
        <fetch distinct="false" no-lock="false" mapping="logical" />
      </main_fetchxml>
      <relatedqueries>
        <fetch distinct="false" no-lock="false" mapping="logical" />
        <fetch distinct="false" no-lock="false" mapping="logical" />
        <fetch distinct="false" no-lock="false" mapping="logical" />
        <fetch distinct="false" no-lock="false" mapping="logical" />
        <fetch distinct="false" no-lock="false" mapping="logical" />
        <fetch distinct="false" no-lock="false" mapping="logical" />
      </relatedqueries>
    </mappings>