C# 从字符串中去除 XML
本文关键字:XML 字符串 | 更新日期: 2023-09-27 18:03:29
我的 xamarin 移动应用程序使用 soap 服务,当我发出登录请求时,返回的响应同时包含 Json 和 xml。我只对 json 字符串感兴趣。任何人都可以告诉我解析以下响应的方法。
[{"Result":"true","HasError":false,"UserMsg":null,"ErrorMsg":null,"TransporterID":"327f6da2-d797-e311-8a6f-005056a34fa8"}]
<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><LoginResponse xmlns="http://tempuri.org/" /></soap:Body></soap:Envelope>
您可以按如下方式使用 Substring
方法:
string response = "<<The response you got>>";
string jsonResponse = response.Substring(0, response.IndexOf("<?"));
0
是起始索引(何时开始提取子字符串(,IndexOf
将返回 <?
的索引,这是响应的 XML 部分的开始。您可以在此处阅读有关Substring
方法的信息。
因此,您已从整个字符串中筛选出 JSON 响应。(有关如何解析 JSON 数据的方法,请查看此答案(。
String.IndexOf
会给你xml部分的索引,然后你可以使用String.Substring
:
string str = @"[{ ""Result"":""true"",""HasError"":false,""UserMsg"":null,""ErrorMsg"":null,""TransporterID"":""327f6da2-d797-e311-8a6f-005056a34fa8""}]
<? xml version = ""1.0"" encoding = ""utf-8"" ?>< soap : Envelope xmlns: soap = ""http://www.w3.org/2003/05/soap-envelope"" xmlns: xsi = ""http://www.w3.org/2001/XMLSchema-instance"" xmlns: xsd = ""http://www.w3.org/2001/XMLSchema"" >< soap:Body >< LoginResponse xmlns = ""http://tempuri.org/"" /></ soap:Body ></ soap:Envelope >";
string json = str.Substring(0, str.IndexOf("<? xml"));
Console.WriteLine(json); // [{ "Result":"true","HasError":false,"UserMsg":D":"327f6da2-d797-e311-8a6f-005056a34fa8"}]