Reputation:
I have a strange problem. When looping through an array and creating XML with XMLWriter and a StringBuilder the strings just stop getting added to the string builder. I don't get any errors until the XmlDoc.LoadXml method is called when I get this error:
Unexpected end of file has occurred. The following elements are not closed: ID, Port, Ports. Line 1256, position 39.
When I stepped though the code the loops continue and throw no errors but nothing is added to the string builder.
Any Ideas? Thanks
public XmlElement LclExportGetPorts()
{
DAL.DALSoapClient soapy = new DAL.DALSoapClient();
DAL.DALStringString[] ports = soapy.EnumPortsWeb(false);
XmlDocument XmlDoc = new XmlDocument();
StringBuilder SB = new StringBuilder();
XmlWriterSettings XmlSettings = new XmlWriterSettings();
XmlSettings.Indent = true;
using (XmlWriter writer = XmlWriter.Create(SB, XmlSettings))
{
writer.WriteStartDocument();
writer.WriteStartElement("Ports");
foreach (var p in ports)
{
writer.WriteStartElement("Port");
writer.WriteElementString("ID", p.Key);
writer.WriteElementString("Name", p.Value);
writer.WriteEndElement();
}
writer.WriteEndElement();
writer.WriteEndDocument();
string temp = writer.ToString();
XmlDoc.LoadXml(SB.ToString());
}
XmlElement Result = XmlDoc.DocumentElement;
return Result;
}
Upvotes: 1
Views: 1408
Reputation: 116108
I think working with Linq2Xml is much more easier. (Also no need to form an xml string first and then parsing it as Wug
suggested)
public XElement LclExportGetPorts()
{
......
XElement xDoc = new XElement("Ports");
foreach (var p in ports)
{
xDoc.Add(new XElement("Port", new XElement("ID", p.ID),
new XElement("Name", p.Name)));
}
return xDoc;
}
Upvotes: 2