簡體   English   中英

System.Xml.XmlException:不能對具有子元素的元素調用 ReadElementContentAs() 方法

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM