Skip to content

Instantly share code, notes, and snippets.

@Microsofttechies
Last active August 29, 2015 14:19
Show Gist options
  • Select an option

  • Save Microsofttechies/df7f045c8e2a8fe1874d to your computer and use it in GitHub Desktop.

Select an option

Save Microsofttechies/df7f045c8e2a8fe1874d to your computer and use it in GitHub Desktop.
XML to string Self-closing element does not fire a EndElement event
XmlTextReader objreader = new XmlTextReader("c:\\a.xml");
StringBuilder strBuilXML = new StringBuilder();
while (objreader.Read())
{
if (objreader.IsStartElement())
{
if (objreader.IsEmptyElement)
{
Console.WriteLine("<{0}/>", objreader.Name);
strBuilXML.Append("<" + objreader.Name);
for (int attInd = 0; attInd < objreader.AttributeCount; attInd++)
{
objreader.MoveToAttribute(attInd);
strBuilXML.Append(" " + objreader.Name + "=");
strBuilXML.Append("\"" + objreader.Value + "\"");
}
strBuilXML.Append(">");
strBuilXML.Append("</" + objreader.Name);
strBuilXML.Append(">");
}
else
{
switch (objreader.NodeType)
{
case XmlNodeType.Element:
strBuilXML.Append("<" + objreader.Name);
for (int attInd = 0; attInd < objreader.AttributeCount; attInd++)
{
objreader.MoveToAttribute(attInd);
strBuilXML.Append(" " + objreader.Name + "=");
strBuilXML.Append("\"" + objreader.Value + "\"");
}
strBuilXML.Append(">");
break;
case XmlNodeType.Text:
string value = objreader.Value;
if (string.IsNullOrEmpty(value))
{
strBuilXML.Append("</" + objreader.Name);
strBuilXML.Append(">");
break;
}
else
strBuilXML.Append(value);
break;
case XmlNodeType.EndElement:
strBuilXML.Append("</" + objreader.Name);
strBuilXML.Append(">");
break;
}
}
}
}
objreader.Close();
Console.WriteLine(strBuilXML);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment