解析不寻常的XML使用LINQ
我得到一个特殊的响应返回从Web服务:解析不寻常的XML使用LINQ
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<GetLemonadeResponse xmlns="http://microsoft.com/webservices/">
<GetLemonadeResult><Response><Status>Error</Status><Message>Could not find the Lemonade for this State/Lemon</Message><FileNumber /></Response></GetLemonadeResult>
</GetLemonadeResponse>
</soap:Body>
</soap:Envelope>
2个问题:
1)我不知道为什么GetLemonadeResult的含量有异常的内容(如“& “)。
我字节迁移到字符串是这样的:
WebClientEx client = new WebClientEx();
client.Headers.Add(HttpRequestHeader.ContentType, "text/xml; charset=utf-8");
client.Encoding = Encoding.UTF8;
byte[] result = client.UploadData(_baseUri.ToString(), data);
client.Encoding.GetBytes(xml));
string resultString = client.Encoding.GetString(result);
(WebClientEx从Web客户端派生一个额外的超时属性)。
我在想,如果我选错了编码,响应的外部部分将以同样的方式被损坏。
Web服务是否有错误?
2)为什么当我尝试使用Linq to XML获取“GetLemonadeResult”时,它无法拉取任何东西?
var xdoc = XDocument.Parse(response); // returns the XML posted above
var responseAsXML = xdoc.Descendants("GetLemonadeResult"); // gets nothing
我根本看不出我需要一个命名空间赶后裔,因为XML GetLemonadeResult标签没有预谋“标签”。
1)能无效的XML像<一些字符,>等被转义
2)你忘了,包括命名空间中的代码
var xdoc = XDocument.Parse(response);
XNamespace soap = "http://schemas.xmlsoap.org/soap/envelope/";
XNamespace ns = "http://microsoft.com/webservices/";
var responseAsXML = xdoc.Descendants(soap + "Body")
.Descendants(ns + "GetLemonadeResult")
.First().Value;
responseAsXML
将
<Response>
<Status>Error</Status>
<Message>Could not find the Lemonade for this State/Lemon
</Message><FileNumber />
</Response>
EDIT
这是SOAP/XML我用来测试
string response = @"<soap:Envelope xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<soap:Body>
<GetLemonadeResponse xmlns=""http://microsoft.com/webservices/"">
<GetLemonadeResult><Response><Status>Error</Status><Message>Could not find the Lemonade for this State/Lemon</Message><FileNumber /></Response></GetLemonadeResult>
</GetLemonadeResponse>
</soap:Body>
</soap:Envelope>";
@micahhoover我在你的问题中使用了soap/xml,它返回了我发布的xml。我编辑了答案。 – I4V 2013-04-24 20:11:16
谢谢。我在我的最后犯了一个愚蠢的错误。信封不需要明确地“下降”。 – micahhoover 2013-04-24 20:20:45
我没有看到 “GetClosingProtectionLetterResult” 在你的例子回应? – cgatian 2013-04-24 19:41:20
'GetClosingProtectionLetterResult'在您提供的示例XML中不存在。请用包含它的XML更新您的问题。 – 2013-04-24 19:41:40
@cgtian:这么多是为了掩饰我来自哪个行业!道歉... – micahhoover 2013-04-24 19:49:37