【发布时间】:2011-05-09 16:04:11
【问题描述】:
XDocuments 和 Linq 的新手,请提出一个从 xml 字符串中的特定标签检索数据的解决方案:
如果我有来自 web 服务响应的 XML 字符串(为方便起见,我格式化了 xml):
<?xml version="1.0" encoding="utf-8"?>
<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>
<GetCashFlowReportResponse xmlns="http://tempuri.org/">
<GetCashFlowReportPdf>Hello!</GetCashFlowReportPdf>
</GetCashFlowReportResponse>
</soap:Body>
</soap:Envelope>
使用下面的代码,我只能在GetCashFlowReportResponse 标签没有"xmlns" 属性的情况下获取值。不知道为什么?否则,它总是返回 null。
string inputString = "<?xml version=\"1.0\" encoding=\"utf-8\"?><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><GetCashFlowReportResponse xmlns=\"http://tempuri.org/\"><GetCashFlowReportPdf>Hello!</GetCashFlowReportPdf></GetCashFlowReportResponse></soap:Body></soap:Envelope>"
XDocument xDoc = XDocument.Parse(inputString);
//XNamespace ns = "http://tempuri.org/";
XNamespace ns = XNamespace.Get("http://tempuri.org/");
var data = from c in xDoc.Descendants(ns + "GetCashFlowReportResponse")
select (string)c.Element("GetCashFlowReportPdf");
foreach (string val in data)
{
Console.WriteLine(val);
}
我无法更改 Web 服务以删除该属性。有没有更好的方法来读取响应并将实际数据返回给用户(以更易读的形式)?
编辑: 解决方案:
XDocument xDoc = XDocument.Parse(inputString);
XNamespace ns = "http://tempuri.org/";
var data = from c in xDoc.Descendants(ns + "GetCashFlowReportResponse")
select (string)c.Element(ns + "GetCashFlowReportPdf");
foreach (string val in data)
{
Console.WriteLine(val);
}
注意:即使所有子元素都没有命名空间属性,如果您将“ns”添加到元素中,代码也会起作用,因为我猜孩子会从父元素继承命名空间(请参阅 SLaks 的回复)。
【问题讨论】:
-
感谢所有回复,但不知道为什么没有返回任何结果。我尝试了所有三种解决方案,结果仍然是相同的“null”。不确定我是否遗漏了什么。更新的代码在我的原始帖子中。我也尝试了“spender”的解决方案,但也返回了 null。有什么想法吗?
标签: c# xml linq-to-xml