[英]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. 我使用的API如果成功则返回XML,如果失败则返回错误字符串。 I would like to find a robust way of determining if a string is XML or just a string. 我想找到一种确定字符串是XML还是只是字符串的可靠方法。 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 尝试解析,如果抛出异常不是xml
string unknow = "";
try
{
return XElement.Parse(unknow);
}
catch (System.Xml.XmlException)
{
return null;
}
One way is to let XDocument
try parsing the input. 一种方法是让XDocument
尝试解析输入。 If the parse is successful, the input is valid XML; 如果解析成功,则输入为有效XML;否则,输入为0。 otherwise, it's not a valid XML. 否则,它不是有效的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. 这是验证XML的相对昂贵的方法。 If you plan to use parsed XML later on, I would change this to TryParse
, and use the output like this: 如果您打算稍后使用解析的XML,我将其更改为TryParse
,并使用如下输出:
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. 一种健壮但缓慢的方法是解析结果( XElement.Parse()
),然后查看它是否引发异常。
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. 较不健壮但快速得多的方法是检查一些基本假设,例如字符串(在修剪空格之后)是否以<>
标记开头和结尾。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.