简体   繁体   中英

Determine whether a given string is XML or not

I am using an API that returns XML if it succeeds and returns an error string if it fails. I would like to find a robust way of determining if a string is XML or just a string. I'd like to know if there is something that already exists in the framework before I try to do it myself.

try to parse, if throw exception is not xml

string unknow = "";
try
{
    return XElement.Parse(unknow);
}
catch (System.Xml.XmlException)
{
    return null;
}

One way is to let XDocument try parsing the input. If the parse is successful, the input is valid XML; otherwise, it's not a valid XML.

Boolean ValidateXml(string xmlString) {
    try {
        return XDocument.Load(new StringReader(xmlString)) != null;
    } catch {
        return false;
    }
}

This is a relatively expensive way of validating XML. If you plan to use parsed XML later on, I would change this to TryParse , and use the output like this:

Boolean TryParseXml(string xmlString, out XDocument res) {
    try {
        res = XDocument.Load(new StringReader(xmlString));
        return true;
    } catch {
        res = null;
        return false;
    }
}

Here is how I would call this method:

XDocument doc;
if (TryParseXml(response, out doc)) {
    // Use doc here
} else {
     // Process the error message
}

A robust--but slow--way would be to parse out the result ( XElement.Parse() )and see if it throws an exception.

public bool IsValidXml(string candidate)
{
    try{
        XElement.Parse(candidate);
    } catch(XmlException) {return false;}
    return true;
}

A less robust, but much more quick way would be to check some basic assumptions, like whether the string (after trimming whitespace) starts and ends with <> tags.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM