Il est impossible de valider le bien-formedness d'une chaîne XML sans l'analyser. Et une référence rapide montre que la façon la plus rapide pour analyser une chaîne pour voir si elle est valide (en fait le moyen le plus rapide pour analyser la chaîne particulière I en utilisant comme un cas de test) est avec un XmlReader:
static void Main(string[] args)
{
const int iterations = 20000;
const string xml = @"<foo><bar><baz a='b' c='d'/><foo><bar><baz a='b' c='d'/></bar><bar/></foo><foo><bar><baz a='b' c='d'/></bar><bar/></foo><foo><bar><baz a='b' c='d'/></bar><bar/></foo><foo><bar><baz a='b' c='d'/></bar><bar/></foo><foo><bar><baz a='b' c='d'/></bar><bar/></foo><foo><bar><baz a='b' c='d'/></bar><bar/></foo><foo><bar><baz a='b' c='d'/></bar><bar/></foo><foo><bar><baz a='b' c='d'/></bar><bar/></foo><foo><bar><baz a='b' c='d'/></bar><bar/></foo></bar><bar/></foo>";
Stopwatch st = new Stopwatch();
st.Start();
for (int i=0; i<iterations; i++)
{
using (StringReader sr = new StringReader(xml))
using (XmlReader xr = XmlReader.Create(sr))
{
while (xr.Read())
{
}
}
}
st.Stop();
Console.WriteLine(String.Format("XmlReader: {0} ms.", st.ElapsedMilliseconds));
st.Reset();
st.Start();
for (int i=0; i<iterations; i++)
{
XElement.Parse(xml);
}
st.Stop();
Console.WriteLine(String.Format("XElement: {0} ms.", st.ElapsedMilliseconds));
st.Reset();
st.Start();
for (int i = 0; i < iterations; i++)
{
XmlDocument d= new XmlDocument();
d.LoadXml(xml);
}
st.Stop();
Console.WriteLine(String.Format("XmlDocument: {0} ms.", st.ElapsedMilliseconds));
st.Reset();
st.Start();
for (int i = 0; i < iterations; i++)
{
using (StringReader sr = new StringReader(xml))
{
XPathDocument d = new XPathDocument(new StringReader(xml));
}
}
st.Stop();
Console.WriteLine(String.Format("XPathDocument: {0} ms.", st.ElapsedMilliseconds));
Console.ReadKey();
}
Sur ma machine XmlReader
est presque deux fois plus rapide que l'une des alternatives. C'est logique. Bien que je n'ai pas utilisé Reflector pour vérifier, je serais très surpris si XmlDocument
, XDocument
, et XPathDocument
n'utilisaient pas tous XmlReader
sous le capot.
Qu'est-ce qui, dans votre cas, est "valide"? Voulez-vous dire juste formé, ou attendez-vous qu'il corresponde à un DTD/schéma? Cela signifie-t-il que vous devez être en mesure de résoudre les ressources référencées? –
Bon point. Je vais modifier ma question. – BuddyJoe
Je me demande si je devrais appeler ma méthode IsProperXml? ou IsWellFormedXml? – BuddyJoe