問題描述
目前,我有以下 c# 代碼從文本中提取值.如果是 XML,我想要其中的值 - 否則,如果不是 XML,它可以只返回文本本身.
字符串數據 = "..."嘗試{返回 XElement.Parse(data).Value;}捕捉(System.Xml.XmlException){返回數據;}
我知道異常在 C# 中很昂貴,所以我想知道是否有更好的方法來確定我正在處理的文本是否為 xml?
我想到了正則表達式測試,但我不認為這是一個更便宜的選擇.請注意,我要求的是一種更便宜的方法.
你可以對
(手寫.)
//長度必須是 XMLif (!string.IsNullOrEmpty(data)){//如果它以 < 開頭修剪后可能是XML//如果字符串全是空格,需要再次進行空檢查.var trimmedData = data.TrimStart();if (string.IsNullOrEmpty(trimmedData)){返回數據;}if (trimmedData[0] == '<'){嘗試{返回 XElement.Parse(data).Value;}捕捉(System.Xml.XmlException){返回數據;}}}別的{返回數據;}
我最初使用的是正則表達式,但 Trim()[0] 與該正則表達式的作用相同.
Currently, I have the following c# code to extract a value out of text. If its XML, I want the value within it - otherwise, if its not XML, it can just return the text itself.
String data = "..."
try
{
return XElement.Parse(data).Value;
}
catch (System.Xml.XmlException)
{
return data;
}
I know exceptions are expensive in C#, so I was wondering if there was a better way to determine if the text I'm dealing with is xml or not?
I thought of regex testing, but I dont' see that as a cheaper alternative. Note, I'm asking for a less expensive method of doing this.
You could do a preliminary check for a < since all XML has to start with one and the bulk of all non-XML will not start with one.
(Free-hand written.)
// Has to have length to be XML
if (!string.IsNullOrEmpty(data))
{
// If it starts with a < after trimming then it probably is XML
// Need to do an empty check again in case the string is all white space.
var trimmedData = data.TrimStart();
if (string.IsNullOrEmpty(trimmedData))
{
return data;
}
if (trimmedData[0] == '<')
{
try
{
return XElement.Parse(data).Value;
}
catch (System.Xml.XmlException)
{
return data;
}
}
}
else
{
return data;
}
I originally had the use of a regex but Trim()[0] is identical to what that regex would do.
這篇關于檢測 XML 的更好方法?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!