【问题标题】:add new lines when generating xml from object从对象生成 xml 时添加新行
【发布时间】:2018-02-01 17:48:11
【问题描述】:

这是代码

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 文档

我的字符串是连续的

xxxxxxxxxx

【问题讨论】:

  • 您的具体问题是什么?
  • 不清楚您想做什么,请在您的意思中添加更多详细信息以“添加下一行”
  • @CamiloTerevinto 我的意思是'\n'

标签: c# xml


【解决方案1】:

您可以使用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();

【讨论】:

  • 没什么,但您希望您的 XML 字符串格式化,这就是您可以使用 XmlTextWriter 的方法。试试吧,把我的例子放在你的代码后面,输出formattedXml 字符串而不是你的s
  • XmlWriter和XmlTextWriter有什么区别?
  • XmlWriterXmlTextWriterabstract 基类,你不能使用它。
  • @Breathing 它应该可以工作,您可以使用添加的代码更新您的问题以及如何显示字符串吗?我的答案中的代码非常完整,您只需在生成 XML 后添加 if 并将您的行 string s = xml.OuterXml; 替换为 string s = string_writer.ToString();
  • 非常感谢! :') 我希望我的最终字符串类似于 `{0}{1} ,然后我可以使用字符串格式来输入值。我怎样才能做到这一点?
猜你喜欢
  • 2013-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-04
  • 2013-01-07
  • 1970-01-01
  • 1970-01-01
  • 2017-12-22
相关资源
最近更新 更多