C# write XML to stream with XmlDocument

Stream outputStream = new MemoryStream();
XmlDocument doc = new XmlDocument();

XmlElement root = doc.CreateElement("packet");
XmlElement type = doc.CreateAttribute("type");
if (this.request)
  type.Value = "request";
else
  type.Value = "response";

root.AppendChild(type);

XmlElement callElement = doc.CreateElement("call");
XmlAttribute funcAttr = doc.CreateAttribute("func");
funcAttr.Value = this.func;
callElement.AppendChild(funcAttr);
root.AppendChild(call);

XmlElement errElement = doc.CreateElement("error");
XmlAttribute noAttr = doc.CreateAttribute("no");
noAttr.Value = this.errorNumber;
XmlAttribute msgAttr = doc.CreateAttribute("msg");
msgAttr.Value = this.errorMessage;
errElement.AppendChild(noAttr);
errElement.AppendChild(msgAttr);
root.AppendChild(errElement);

XmlElement[] parameterList = new XmlElement[parameterNames.Count];
for (int i = 0; i < this.parameterNames.Count; i++)
{
  parameterList[i] = doc.CreateElement("parameter");
  XmlAttribute nameAttr = doc.CreateAttribute("name");
  nameAttr.Value = parameterNames[i];
  XmlAttribute valueAttr = doc.CreateAttribute("value");
  valueAttr.Value = parameterValues[i];
  parameterList[i].AppendChild(nameAttr);
  parameterList[i].AppendChild(valueAttr);
  root.AppendChild(parameterList[i]);
}

doc.AppendChild(root);
XmlWriter writer = new System.Xml.XmlTextWriter(outputStream, System.Text.Encoding.UTF8);
doc.WriteTo(writer);

 

Dette indlæg blev udgivet i Knowledge Base, Old Base, Programmering. Bogmærk permalinket.

Skriv et svar