在xml表达式中使用循环foreach

时间:2014-03-25 22:22:13

标签: c# xml loops

帮我解决这个问题!我需要创建xml文件。我的xml文件的元素我从文本文件中隔离(config screenos juniper)。我想要关键词,它将作为节点及其元素。

我想实现这样的输出(xml文件):

<VR1>

   <...>

</VR1>
<VR2>

   <...>

</VR2>
<VR3>

   <...>

</VR3>   

但我只有这样的输出:

    <VR3>

       <...>

   </VR3> 

此类代码:

                foreach (var match in myCollection)
            {

                StringWriter stringwriter = new StringWriter();

                XmlTextWriter xmlTextWriter = new XmlTextWriter(stringwriter);
                xmlTextWriter.Formatting = Formatting.Indented;
                xmlTextWriter.WriteStartDocument();
                xmlTextWriter.WriteStartElement(match);
                ;
                             ...
                             ...

                xmlTextWriter.WriteEndElement();
                xmlTextWriter.WriteEndDocument();
                XmlDocument docSave = new XmlDocument();
                docSave.LoadXml(stringwriter.ToString());
                //write the path where you want to save the Xml file
                docSave.Save(AppDomain.CurrentDomain.BaseDirectory.ToString() +"Roting.xml");
            }

这里myCollection包含:VR1,VR2,VR3。 很明显我使用loop foreach 是错误的,但我无法理解如何在此上下文中正确使用它。

1 个答案:

答案 0 :(得分:1)

            StringWriter stringwriter = new StringWriter();

            XmlTextWriter xmlTextWriter = new XmlTextWriter(stringwriter);
            xmlTextWriter.Formatting = Formatting.Indented;
            xmlTextWriter.WriteStartDocument();           

        foreach (var match in myCollection)
        {


            xmlTextWriter.WriteStartElement(match);
            ;
                         ...
                         ...

            xmlTextWriter.WriteEndElement();

        }
            xmlTextWriter.WriteEndDocument();
            XmlDocument docSave = new XmlDocument();
            docSave.LoadXml(stringwriter.ToString());
            //write the path where you want to save the Xml file
            docSave.Save(AppDomain.CurrentDomain.BaseDirectory.ToString() +"Roting.xml");