Testing xml string is well formed xml

C

CodeRazor

Is there a snazzy linq way (or failing that, just a .net 2 way) of testing
whether an xml string is well-formed xml.

I have an xml string which is created on the fly. I am encoding illegal xml
characters as i build it -- but i'm not 100% sure i've taken into account
every illegal xml character....., see below for my efforts. so i want to test
that the xml string is well formed.

public static string EncodeForXml ( string text_value )
{
string returnValue = string.Empty;
int index = 0;

// Return a blank string if we have been passed a null parameter
if (text_value == null)
return string.Empty;

// Encode the illegal characters
while (index < text_value.Length)
{
if (text_value[index] < 32)
returnValue += string.Empty;
else if (text_value[index] > 126)
returnValue += string.Format("&{0};",
((int)text_value[index]).ToString());
else if (text_value[index] == '&')
returnValue += "&";
else if (text_value[index] == '<')
returnValue += "<";
else if (text_value[index] == '>')
returnValue += ">";
else if (text_value[index] == '"')
returnValue += "&quot";
else if (text_value[index] == '\'')
returnValue += "&apos";
else
returnValue += text_value[index];

index++;
}

// Return the encoded text value
return returnValue;
}

I know i can try loading the xml string to create an xml document.
see below, but is there a smarter way that anyone knows of?

System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
try { doc.LoadXml(myXmlString); }
catch { /* malformed xml */ }

thanks.

CodeRazor
 
M

Marc Gravell

It would be more efficient to check xml using XmlReader:

using (XmlReader reader = XmlReader.Create(source))
{
while (reader.Read()) { }
reader.Close();
}

However, I strongly suggest not attempting to do your own escaping -
that is why XmlWriter exists.

Additionally, if you are doing string concatenation in a loop, use
StringBuilder, not concatenation.

Marc
 
M

Marc Gravell

Example:

string xml;
using (StringWriter sw = new StringWriter())
{
using (XmlWriter xw = XmlWriter.Create(sw))
{
xw.WriteStartElement("foo");
xw.WriteStartElement("bar");
xw.WriteAttributeString("attrib", ">>> eek <<<");
xw.WriteElementString("element", "if x < y do
something & then quit");
xw.WriteEndElement();
xw.WriteEndElement();
xw.Close();
}
xml = sw.ToString();
}
Console.WriteLine(xml);

Marc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top