473,385 Members | 1,907 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Testing xml string is well formed xml

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

Sep 12 '08 #1
2 2301
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
Sep 12 '08 #2
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
Sep 12 '08 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Urs Muntwyler | last post by:
Hi there I have to check if the content of a file is a well-formed XML document. Since the XML documents can be large, I'm using SAX to perform this task. Using Java, my code looks (somehow)...
51
by: Alan | last post by:
hi all, I want to define a constant length string, say 4 then in a function at some time, I want to set the string to a constant value, say a below is my code but it fails what is the correct...
9
by: Aaron | last post by:
I need some help writing a function that converts "name:john" into "<name>john</name>" it should be compatible with different tags, not just names "name:john"
17
by: clintonG | last post by:
I'm using an .aspx tool I found at but as nice as the interface is I think I need to consider using others. Some can generate C# I understand. Your preferences please... <%= Clinton Gallagher ...
5
by: feng | last post by:
OK, all I want is writting a string that represents an XML document into a file, say C:\test.xml. This kind of task used to be so easy with vb6. But now, with VB.Net, it seems turned into a big...
2
by: DotNetGruven | last post by:
We have a web service that returns a string which happens to be well formed XML. The client sees the string ok, except the angle brackets are HTML encoded ( &gt and &lt ). Is this expected...
33
by: genc_ymeri | last post by:
Hi over there, Propably this subject is discussed over and over several times. I did google it too but I was a little bit surprised what I read on internet when it comes 'when to use what'. Most...
2
by: Arpan | last post by:
I came across the following statement at http://windowssdk.msdn.microsoft.com/en-us/library/hdf992b8.aspx: Although an XML document is considered to be well formed if it meets all the...
7
by: Daniel | last post by:
what encoding does system.xml.xmldocument.save(string path) use to save the xml document if there is no <?xml... in the front of the xml document?
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.