从c#中的列表<string>创建xml文档

时间:2015-07-22 12:12:39

标签: c# xml xmldocument

我有一个列表&#34; fetchXmlList&#34;包含不同fetch xmls的字符串。我想使用此列表创建xml文档。

Xml文档如下所示:

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

对于相关查询xml节点,我将不得不添加foreach循环并迭代从第二个列表项开始直到列表末尾的每个列表项。

我开始编写以下代码行:

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

但是将列表项追加到XmlElement对象是不允许的。还有其他办法吗?

任何帮助将不胜感激。提前谢谢。

2 个答案:

答案 0 :(得分:0)

您可以使用:

viewDidLoad

答案 1 :(得分:-1)

1)你必须有一个根元素

2)试试这段代码

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");
}

也将导致:

<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>
相关问题