![](/img/trans.png)
[英]C# deserialize xml error ReadElementContentAs() methods cannot be called on an element that has child elements
[英]System.Xml.XmlException: ReadElementContentAs() methods cannot be called on an element that has child elements
我查看了C# 反序列化 xml 错误 ReadElementContentAs() 方法不能在具有子元素的元素上调用,但我的情况似乎有所不同。
XML 我正在尝试使用看起来像:
<SampleXML>
<SomeElement1>SomeValue1</SomeElement1>
<SomeElement2>SomeValue2</SomeElement2>
<RepetitiveElements>
<Id>SomeId1</Id>
<Value>SomeValue1</Value>
</RepetitiveElements>
<RepetitiveElements>
<Id>SomeId2</Id>
<Value>SomeValue2</Value>
</RepetitiveElements>
<RepetitiveElements>
<Id>SomeId3</Id>
<Value>SomeValue3</Value>
</RepetitiveElements>
</SampleXML>
用 C# 编写的 class 是这样的:
[Serializable]
public class MyClass
{
[XmlElement("SomeValue1", Namespace = "")]
public string SomeValue1 { get; set; }
[XmlElement("SomeValue2", Namespace = "")]
public string SomeValue2 { get; set; }
[XmlElement("RepetitiveElements", Namespace = "")]
public List<RepetitiveElements> RepetitiveElements { get; set; }
}
[Serializable]
public class RepetitiveElements
{
[XmlElement("Id", Namespace = "")]
public string Id { get; set; }
[XmlElement("Value", Namespace = "")]
public string Value { get; set; }
}
我在这里想要实现的是,在 MyClass.RepetitiveElements 列表中拥有来自 XML 的所有 RepetitiveElements。 问题是反序列化以“System.Xml.XmlException: ReadElementContentAs() 方法不能在具有子元素的元素上调用”结束。 例外。
任何想法或建议表示赞赏。
此代码适用于发布的示例 xml
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace ConsoleApplication166
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
XmlReader reader = XmlReader.Create(FILENAME);
XmlSerializer serializer = new XmlSerializer(typeof(MyClass));
MyClass myClass = (MyClass)serializer.Deserialize(reader);
}
}
[XmlRoot("SampleXML")]
public class MyClass
{
[XmlElement("SomeValue1", Namespace = "")]
public string SomeElement1 { get; set; }
[XmlElement("SomeElement2", Namespace = "")]
public string SomeValue2 { get; set; }
[XmlElement("RepetitiveElements", Namespace = "")]
public List<RepetitiveElements> RepetitiveElements { get; set; }
}
[Serializable]
public class RepetitiveElements
{
[XmlElement("Id", Namespace = "")]
public string Id { get; set; }
[XmlElement("Value", Namespace = "")]
public string Value { get; set; }
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.