C# WCF服务方法仅返回数组首个字符串问题排查
问题分析与修复方案
核心错误点
- 遍历提前终止:
ReadXmlDocument_Navires方法的foreach循环中,第一次迭代就执行return,导致仅能读取第一个<Navire>节点的内容,后续节点完全未处理。 - 数组仅含单个元素:服务方法
NaviresXml中,return new string[] { x.ReadXmlDocument_Navires() }是把单个字符串包装成数组,无论原方法能返回多少内容,数组永远只有一个元素。
修复后的代码
1. 修改XMLReader类的ReadXmlDocument_Navires方法
改为收集所有节点的内容,而非仅返回第一个:
public class XMLReader { public string XmlFilePath { get; set; } public XMLReader(string XmlFilePath) { this.XmlFilePath = XmlFilePath; } public List<string> ReadXmlDocument_Navires() { List<string> navireList = new List<string>(); XmlDocument xmlDoc1 = new XmlDocument(); xmlDoc1.Load(XmlFilePath); XmlNodeList itemNodes = xmlDoc1.GetElementsByTagName("Navire"); foreach (XmlElement node in itemNodes) { // 增加属性空值判断,避免空引用异常 if (node.Attributes["Type"] != null && node.Attributes["Nom"] != null) { navireList.Add("Navire" + node.Attributes["Type"].Value + "Nom" + node.Attributes["Nom"].Value); } } return navireList; } }
2. 修改服务实现方法NaviresXml
将收集到的列表转为数组返回:
public string[] NaviresXml() { try { XMLReader x = new XMLReader(FilePath); return x.ReadXmlDocument_Navires().ToArray(); } catch (Exception ex) { // WCF中建议使用FaultException替代普通Exception,避免暴露过多服务内部细节 throw new FaultException(ex.Message + "\n" + ex.StackTrace); } }
修复说明
修改后,ReadXmlDocument_Navires会遍历所有<Navire>节点,将每个节点的拼接字符串存入列表,最终服务方法将列表转为数组返回,就能得到包含所有目标字符串的数组。
内容的提问来源于stack exchange,提问作者Jeff Collombet
相关产品推荐
相关产品推荐

