如何使用LINQ读取XML字符串并提取IntervalStartTime存入DateTime变量
解决方案
错误原因
- 加载方法错误:
XDocument.Load()用于读取文件/网络URI,读取XML字符串需要使用XDocument.Parse(),这是你报UriFormatException的直接原因 - 未处理命名空间:你的SOAP XML不同层级节点属于不同命名空间,直接使用元素名查询无法匹配对应节点
- 元素名格式错误:查询
PlantForecastIntervalNode时不需要加尖括号
修正后代码
string soapmessage = @"<?xml version=""1.0"" encoding=""UTF - 8""?>" + "\n" + response.Content; // 1. 用Parse读取XML字符串,而非Load XDocument xdoc = XDocument.Parse(soapmessage); // 2. 定义各层级节点对应的命名空间 XNamespace nsSoap = "http://schemas.xmlsoap.org/soap/envelope/"; XNamespace nsTempuri = "http://tempuri.org/"; XNamespace nsLss = "LSS.solar.webservice"; XNamespace nsBase = "http://base.datacontract"; // 3. 按层级+命名空间查询,取第一个节点的时间值转DateTime string timeStr = xdoc.Element(nsSoap + "Envelope") .Element(nsSoap + "Body") .Element(nsTempuri + "FourMonthsAhead1Response") .Element(nsLss + "FourMonthsAhead1Result") .Element(nsBase + "PlantForecastIntervals") .Elements(nsBase + "PlantForecastIntervalNode") .First() .Element(nsBase + "IntervalStartTime") .Value; DateTime intervalStartTime = DateTime.Parse(timeStr); Console.WriteLine(intervalStartTime); Console.ReadLine();
补充说明
如果需要兼容节点不存在的异常场景,可以把First()替换为FirstOrDefault()增加非空判断,避免空引用异常;如果时间格式存在不标准的可能,可以用DateTime.TryParse()替代DateTime.Parse()做容错处理。
内容的提问来源于stack exchange,提问作者Daniel
相关产品推荐
相关产品推荐

