我真的不建议用字符串连接这样做是为了使用。有很多不同的方法可以实现这一点,从而产生更好的结果(因为不太可能产生格式不正确的XML)。
通过XmlTextWriter:
string xmlString = null;
using (StringWriter xmlOutput = new StringWriter())
using(XmlTextWriter xmlWriter = new XmlTextWriter(xmlOutput))
{
xmlWriter.WriteStartDocument();
xmlWriter.WriteStartElement("product");
xmlWriter.WriteElementString("name", pName);
xmlWriter.WriteElementString("price", pPrice);
xmlWriter.WriteEndElement();
xmlString = xmlOutput.ToString();
}
使用XmlDocument:
string xmlString = null;
using (StringWriter xmlOutput = new StringWriter())
{
XmlDocument xmlDocument = new XmlDocument();
XmlElement productElement = xmlDocument.CreateElement("product");
XmlElement nameElement = xmlDocument.CreateElement("name");
nameElement.InnerText = pName;
XmlElement priceElement = xmlDocument.CreateElement("price");
priceElement.InnerText = pPrice;
productElement.AppendChild(nameElement);
productElement.AppendChild(priceElement);
xmlDocument.AppendChild(productElement);
xmlDocument.Save(xmlOutput);
xmlString = xmlOutput.ToString();
}
使用XDocument(要求您使用的是.NET 3.5或更高版本)的这些
XDocument xml = new XDocument(
new XElement("product",
new XElement("name", pName),
new XElement("price", pPrice)
)
);
string xmlString = xml.ToString();
注只有使用XmlTextWriter的方法才会使用流这对于非常大的XML组合非常重要。如果您使用的是.NET 3.5或更高版本,并且没有处理非常大的XML组合,那么我会优先使用XDocument,因为它更易读易用。
在问这个问题之前,你看过** String.Format **吗?你的问题显示你完全缺乏研究。在C#中构建字符串是一项非常简单的任务。 – 2012-02-21 18:18:20
非常抱歉的noob问题...我会研究一下,谢谢! – marcPerry 2012-02-21 18:28:49
如果您使用XML代表代码中的对象,我建议您查看XML序列化。 – walkingTarget 2012-02-21 18:47:50