Я бы сказал, что их API ненадежен. Я только что проверил его для domain=getpostman.com
, и он сообщает "available": true
, хотя, безусловно, это не так.
{
"available": true,
"currency": "USD",
"definitive": true,
"domain": "getpostman.com",
"period": 1,
"price": 10690000
}
Согласно документам , «доступные» и «окончательные» значения должны указывать, что они абсолютно уверены в том, доступно или нет доменное имя.
DomainAvailableResponse
доступно * логическое Доступно или нет доменное имя
окончательное * логическое Независимо от того, была ли окончательно подтверждена доступная информация реестр
blockquote>
кавычка:
public static string GetXPathString(string input) {
string[] fragments = input.Split(new char[] { ‘\” });
string result = “”;
result += “concat(””;
for (int i = 0; i < fragments.Length; i++)
{
result += “, ‘” + fragments[i] + “‘”;
if (i < fragments.Length - 1)
{
result += “, \”‘\”";
}
}
result += “)”;
return result;
}
И вот то, как Вы изменяете вышеупомянутый код, чтобы использовать нашу новую функцию://не забывают удалять одинарные кавычки после = и]
XmlNode n = doc.SelectSingleNode(“/root/emp[@lname=" + GetXPathString(ln) + "]“);
Или просто любят предыдущее предложенное сообщение. сделайте легкую замену func 'и "с & apos; и & кавычка;
Хотя это, конечно, не будет работать при всех обстоятельствах, вот способ обойти проблему:
doc.DocumentElement.SetAttribute("searchName", name);
XmlNode n = doc.SelectNodes("//review[@name=/*/@searchName]");
Я нуждался в этом так, я создал это решение для C#.
/// <summary>
/// Returns a valid XPath statement to use for searching attribute values regardless of 's or "s
/// </summary>
/// <param name="attributeValue">Attribute value to parse</param>
/// <returns>Parsed attribute value in concat() if needed</returns>
public static string GetXpathStringForAttributeValue(string attributeValue)
{
bool hasApos = attributeValue.Contains("'");
bool hasQuote = attributeValue.Contains("\"");
if (!hasApos)
{
return "'" + attributeValue + "'";
}
if (!hasQuote)
{
return "\"" + attributeValue + "\"";
}
StringBuilder result = new StringBuilder("concat(");
StringBuilder currentArgument = new StringBuilder();
for (int pos = 0; pos < attributeValue.Length; pos++)
{
switch (attributeValue[pos])
{
case '\'':
result.Append('\"');
result.Append(currentArgument.ToString());
result.Append("'\",");
currentArgument.Length = 0;
break;
case '\"':
result.Append('\'');
result.Append(currentArgument.ToString());
result.Append("\"\',");
currentArgument.Length = 0;
break;
default:
currentArgument.Append(attributeValue[pos]);
break;
}
}
if (currentArgument.Length == 0)
{
result[result.Length - 1] = ')';
}
else
{
result.Append("'");
result.Append(currentArgument.ToString());
result.Append("')");
}
return result.ToString();
}
Это - то, что я придумал
public static string EncaseXpathString(string input)
{
// If we don't have any " then encase string in "
if (!input.Contains("\""))
return String.Format("\"{0}\"", input);
// If we have some " but no ' then encase in '
if (!input.Contains("'"))
return String.Format("'{0}'", input);
// If we get here we have both " and ' in the string so must use Concat
StringBuilder sb = new StringBuilder("concat(");
// Going to look for " as they are LESS likely than ' in our data so will minimise
// number of arguments to concat.
int lastPos = 0;
int nextPos = input.IndexOf("\"");
while (nextPos != -1)
{
// If this is not the first time through the loop then seperate arguments with ,
if (lastPos != 0)
sb.Append(",");
sb.AppendFormat("\"{0}\",'\"'", input.Substring(lastPos, nextPos - lastPos));
lastPos = ++nextPos;
// Find next occurance
nextPos = input.IndexOf("\"", lastPos);
}
sb.Append(")");
return sb.ToString();
}
Названный использованием чего-то как
XmlNode node = doc.SelectSingleNode("//review[@name=" + EncaseXpathString("Fred's \"Fancy Pizza\"" + "]")
, Таким образом, мы получаем следующие результаты
EncaseXpathString("Pizza Shed") == "'Pizza Shed'";
EncaseXpathString("Bob's pizza") == "\"Bob's Pizza\"";
EncaseXpathString("\"Pizza\" Pam" == "'\"Pizza\" Pam'";
EncaseXpathString("Fred's \"Fancy Pizza\"") == "concat(\"Fred's \",'\"',\"Fancy Pizza\",'\"')";
, Таким образом, оно только использует concat, когда его необходимое (и "и 'в строке)
последнее шоу результата, concat операция не так коротка, как это могло быть (см. вопрос), но его достаточно близкое и что-либо более оптимальное были бы очень сложны, поскольку необходимо будет искать соответствие парам" или'.
Другой вариант ... моя часть concat () немного ленивая, но, по крайней мере, она использует все значение.
/// <summary>
/// Returns an XPath string literal to use for searching attribute values (wraped in apostrophes, quotes, or as a concat function).
/// </summary>
/// <param name="attributeValue">Attribute value to encode and wrap.</param>
public static string CreateXpathLiteral(string attributeValue)
{
if (!attributeValue.Contains("\""))
{
// if we don't have any quotes, then wrap string in quotes...
return string.Format("\"{0}\"", attributeValue);
}
else if (!attributeValue.Contains("'"))
{
// if we have some quotes, but no apostrophes, then wrap in apostrophes...
return string.Format("'{0}'", attributeValue);
}
else
{
// must use concat so the literal in the XPath will find a match...
return string.Format("concat(\"{0}\")", attributeValue.Replace("\"", "\",'\"',\""));
}
}