Reputation: 1237
How do I test if the closing tags are available:
e.g.
<A>
<n>
<r>
</r>
<b>
</b>
In the above case I'm missing the </A>
and </n>
closing tags.
How do I check for this ?
CODE:
try
{
XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(FileName);
}
catch (XmlException xe)
{
XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(FileName);
xdoc.AppendChild(xdoc.CreateElement("/n"));
xdoc.AppendChild(xdoc.CreateElement("/A"));
}
But it's giving me an exception : data at the root is invalid. The xml is missing the closing tags for /n and /A. Please advise.
EDIT 2:
try
{
XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(FileName);
}
catch (XmlException xe)
{
using (StreamWriter w = File.AppendText(FileName))
{
w.WriteLine("</n>");
w.WriteLine("</A>");
}
}
Now with Edit 2, it goes and corrects the filename with the missing tags. But what if the xml already has available it still goes in and put's in another tag /n /A and gives me exception: unexpected end tag.
Upvotes: 0
Views: 2045
Reputation: 978
Load it in an XmlDocument, Put a try-catch around it, if there is any exception it means there's something wrong with your XML string (Missing closing tags, invalid characters etc) -
try{
XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(xmlString);
}
catch (XmlException xe)
{
System.Windows.Forms.MessageBox.Show(xe.Message);
}
Upvotes: 3