从对象生成xml时添加新行

时间:2018-02-01 09:23:36

标签: c# xml

这是代码

XmlDocument xml = new XmlDocument();
XmlElement root = xml.CreateElement("customers");
xml.AppendChild(root);
foreach (var cust in customerlist)
{
    XmlElement child = xml.CreateElement("customer");
    child.SetAttribute("CustomerId", cust.CustomerId.ToString());
    child.SetAttribute("CustomerName", cust.CustomerName);
    child.SetAttribute("PhoneNumber", cust.PhoneNumber);
    child.SetAttribute("Email", cust.Email);
    root.AppendChild(child);
}
string s = xml.OuterXml;

我希望我的字符串添加下一行而不是单个xml文档

我的字符串是连续的

  

< x> xxxxx< / x> < x> xxxxx< / x>

1 个答案:

答案 0 :(得分:2)

您可以使用XmlTextWriter类将XML格式化为如下字符串:

StringWriter string_writer = new StringWriter();
XmlTextWriter xml_text_writer = new XmlTextWriter(string_writer);
xml_text_writer.Formatting = Formatting.Indented;
xml.WriteTo(xml_text_writer); // xml is your XmlDocument

string formattedXml = string_writer.ToString();