获取字符串节点值

 获取Json字符串某节点的值
/// <summary>
/// 获取Json字符串某节点的值
/// </summary>
public static string GetJsonValue(string jsonStr, string key)
{
string result = string.Empty;
if (!string.IsNullOrEmpty(jsonStr))
{
key = "\"" + key.Trim('"') + "\"";
int index = jsonStr.IndexOf(key) + key.Length + 1;
if (index > key.Length + 1)
{
//先截逗号,若是最后一个,截“}”号,取最小值
int end = jsonStr.IndexOf(',', index);
if (end == -1)
{
end = jsonStr.IndexOf('}', index);
}

result = jsonStr.Substring(index, end - index);
result = result.Trim(new char[] { '"', ' ', '\'' }); //过滤引号或空格
}
}
return result;
}

 

获取XML字符串某节点的值
/// <summary>
/// XML KEY 通用方法
/// </summary>
/// <returns></returns>
public static string GetXMLstrByKey(string Key, XmlDocument xml)
{
object strValue = xml.SelectSingleNode("xml").SelectSingleNode(Key).InnerText;
if (strValue != null)
{
return strValue.ToString();
}
else
{
return "";
}
}

 

手动解析XML字符串

public string GetXmlNodeValue(string xml, string NodeName)
{
int m, n;
string sValue = "";
string xml0 = xml;
//转换成大写
xml = xml.ToUpper();
NodeName = NodeName.ToUpper();
n = xml.IndexOf("<" + NodeName);
//找到字符串的开始符"<"和结束符"/>",再取出其值
if (n >= 0)
{
for (int i = n + NodeName.Length + 1; i < xml.Length; i++)
{
string c = xml.Substring(i, 1);
if (c == ">")
{
m = xml.IndexOf("</" + NodeName + ">", i + 1);
if (m >= 0)
{
sValue = xml0.Substring(i + 1, m - i - 1);
break;
}

}
else if (c == "/")
{
sValue = "";
break;
}
else if (c == " ")
{

}
else
{
//不正常的结束符号
sValue = "";
break;
}
}
}
//除去空格
return sValue.Trim();
}

posted on 2019-04-15 15:38 只想愛你 阅读(...) 评论(...) 编辑 收藏

导航

统计