如何将XML字符串转为C#对象并仅读取指定节点(报错求助)
解决XML反序列化"未预期的内容"错误
错误原因
你的XML根节点是<root>,但当前XmlSerializer初始化时传入的是LocationSettings类型,该类标记了[XmlRoot("locationsettings")],序列化器期望根节点为<locationsettings>,同时XML中存在<main>等未定义的节点,导致反序列化时触发错误。此外,LocationSettings类中RowSettings的特性使用有误:XML里<locationsettings>直接包含多个<row>节点,而[XmlArrayItem("row")]需要配合外层数组节点(如<rows>)使用,当前特性无法正确匹配XML结构。
解决方案
方案一:提取目标节点后反序列化
先加载整个XML,定位到<locationsettings>节点,再对该节点的XML内容进行反序列化:
var xmlSettings = $"<?xml version=\"1.0\"?>{item.Settings}"; var doc = new XmlDocument(); doc.LoadXml(xmlSettings); // 提取locationsettings节点 var locationNode = doc.SelectSingleNode("//locationsettings"); if (locationNode != null) { var locationXml = locationNode.OuterXml; using var stringReader = new StringReader(locationXml); var serializer = new XmlSerializer(typeof(LocationSettings)); var tt = serializer.Deserialize(stringReader) as LocationSettings; }
同时修正LocationSettings类的特性,将[XmlArrayItem("row")]改为[XmlElement("row")]:
[Serializable] public class LocationSettings { public LocationSettings() { this.RowSettings = new List<RowSettings>(); } // 直接匹配locationsettings下的row节点 [XmlElement("row")] public List<RowSettings> RowSettings { get; set; } } [Serializable] public class RowSettings { [XmlElement("dealerid")] public int dealerid { get; set; } [XmlElement("locationid")] public int locationid { get; set; } [XmlElement("ikquserid")] public string? ikquserid { get; set; } [XmlElement("ikqpass")] public string? ikqpass { get; set; } }
方案二:定义根节点类匹配完整XML结构
创建一个匹配<root>节点的类,仅定义需要的LocationSettings属性,序列化器会自动忽略未定义的<main>节点:
// 根节点类 [Serializable, XmlRoot("root")] public class RootXml { [XmlElement("locationsettings")] public LocationSettings LocationSettings { get; set; } } // 修正后的LocationSettings类 [Serializable] public class LocationSettings { public LocationSettings() { this.RowSettings = new List<RowSettings>(); } [XmlElement("row")] public List<RowSettings> RowSettings { get; set; } } // RowSettings类保持不变 [Serializable] public class RowSettings { [XmlElement("dealerid")] public int dealerid { get; set; } [XmlElement("locationid")] public int locationid { get; set; } [XmlElement("ikquserid")] public string? ikquserid { get; set; } [XmlElement("ikqpass")] public string? ikqpass { get; set; } }
然后直接反序列化整个XML:
var xmlSettings = $"<?xml version=\"1.0\"?>{item.Settings}"; using var stringReader = new StringReader(xmlSettings); var serializer = new XmlSerializer(typeof(RootXml)); var root = serializer.Deserialize(stringReader) as RootXml; var tt = root?.LocationSettings;
内容的提问来源于stack exchange,提问作者Muhammad Kamran
相关产品推荐
相关产品推荐

