Web请求发送到url
,然后响应返回如下:
- <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
- <soap:Body>
- <ns2:operationResponse xmlns:ns2="">
<return>
<response>
<header>
<uname></uname>
<pass></pass>
<sp></sp>
<ss></ss>
<trx></trx>
<headerdtl></headerdtl>
</header>
<respcd>8913|9|8915|1;Record already existed!!|</respcd>
<rcdcnt>0</rcdcnt>
</response>
</return>
</ns2:operationResponse>
</soap:Body>
</soap:Envelope>
我想要的是阅读|number|
<respcd>8913|number|8915|1;Record already existed!!|</respcd>
此值不保持不变,返回0或9.如何使用c#
读取该值 Update
我有这段代码:
int index = xmlString.IndexOf("<response>");
xmlString = xmlString.Substring(index, xmlString.Length - index);
index = xmlString.IndexOf("</return>");
xmlString = xmlString.Substring(0, index);
但错误说:StartIndex cannot be less than zero
在这一行xmlString = xmlString.Substring(index, xmlString.Length - index);
我知道索引现在是-1
,但它是..任何想法的实际索引?
答案 0 :(得分:1)
一种方法是加载XML,从节点获取文本,并解析出您想要的值。但是,如果您想要的值足够独特,您可以从一开始就使用RegEx并忘记加载XML。以下是两种方法:
加载XML
string soapmessage = @"
<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>
<soap:Body>
<ns2:operationResponse xmlns:ns2='http://someurl.com'>
<return>
<response>
<header>
<uname></uname>
<pass></pass>
<sp></sp>
<ss></ss>
<trx></trx>
<headerdtl></headerdtl>
</header>
<respcd>8913|9|8915|1;Record already existed!!|</respcd>
<rcdcnt>0</rcdcnt>
</response>
</return>
</ns2:operationResponse>
</soap:Body>
</soap:Envelope>
";
XmlDocument document = new XmlDocument();
document.LoadXml(soapmessage);
XmlNodeList xnList = document.SelectNodes("//respcd");
XmlNode node = xnList.Cast<XmlNode>().FirstOrDefault();
string value = Regex.Match(node.InnerText, "(?<=|)[09](?=|)").Value;
Console.WriteLine(value); //<== writes out 9.
仅使用RegEx
string value2 = Regex.Match(soapmessage, "(?<=|)[09](?=|)").Value;
Console.WriteLine(value2); //<== writes out 9.
注意我将xmlns:ns2=""
部分更改为xmlns:ns2="http://someurl.com"
,因为加载XML方法因为没有正确定义名称空间而引发错误。
答案 1 :(得分:0)
试试这个
XmlNode nListAuthor = doc.SelectNodes("//respcd")[0];
string Output = string.Empty;
if (nListAuthor != null)
{
if (Regex.IsMatch(nListAuthor.InnerText, @"^(?:[0-9]+\|([0-9])\|[0-9]+\|(.*)\|)$", RegexOptions.IgnoreCase))
{
Output = Regex.Match(nListAuthor.InnerText, @"^(?:[0-9]+\|([0-9])\|[0-9]+\|(.*)\|)$", RegexOptions.IgnoreCase).Groups[1].Value;
}
}