将xml字符串写入新创建的xml文件

时间:2016-07-09 19:08:52

标签: xml c#-4.0

我有一个XML格式的字符串。我需要创建一个新的xml文件并将其写入其中。 这是我试图实现的代码:

StringBuilder xmlBuilder = new StringBuilder();
            string name = string.Empty;
            string district = string.Empty;

            xmlBuilder.Append("<AddressInfo>");

            foreach (City item in data)
            {
                if (district != string.Empty && item.district != district)
                {
                    xmlBuilder.Append("</District>");
                }     
            }
            ...
            xmlBuilder.Append("</District>");
            xmlBuilder.Append("</AddressInfo>");

            XmlSerializer serializer = new XmlSerializer(xmlBuilder.GetType());
            using (TextWriter writeFileStream = new StreamWriter(Path.Combine(HttpRuntime.AppDomainAppPath, "App_Data", "output.xml")))
            {
                serializer.Serialize(writeFileStream, xmlBuilder.ToString());
            }

当然它不起作用,如何将此字符串写入xml文件?

1 个答案:

答案 0 :(得分:0)

使用XML Linq

尝试这样的事情
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            List<City> data = new List<City>() {
                new City() { district = "district1"},
                new City() { district = "district2"},
                new City() { district = "district3"},
                new City() { district = "district4"}
            };

            string header = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><AddressInfo></AddressInfo>";

            XDocument doc = XDocument.Parse(header);
            XElement addressInfo = (XElement)doc.FirstNode;

            foreach(City city in data)
            {
                addressInfo.Add(new XElement("District", city.district)); 
            }

        }
    }
    public class City
    {
        public string district { get; set; }

    }

}