0

これが私のDTOです

[XmlTypeAttribute(TypeName="XAttributes")]
public class XAttributes
{
    [XmlArray(ElementName="Attributes")]
    [XmlArrayItem(ElementName="Attribute")]
    public List<Attribute> Attributes { get; set; }    
    public XAttributes()
    {
        Attributes = new List<Attribute>();
    }
}
public class Attribute
{      
    [XmlElement(ElementName = "Name")]
    public string Name { get; set; }

    [XmlElement(ElementName = "Value")]
    public string Value { get; set; }      

    [XmlElement(ElementName = "ValueType")]
    public ValueType ValueType {get; set; }

    [XmlArray(ElementName="Children" )]
    public List<Attribute> Children { get; set; }
}

ここに私の逆シリアル化コードがあります

  public static T ToObject<T>(this string XMLData)
    {
        var s = new XmlSerializer(typeof(T));
        object obj=null;
        using (var sr = new StringReader(XMLData))
        {
            obj = s.Deserialize(sr);
        }
        return (T)obj;
    }

そして、ここに私がそれを逆シリアル化するために呼び出すコードがあります

string attr = @"<XAttributes><Attributes>                          
                        <Attribute>
                        <Name>Test</Name>
                        <Value>TestVlau</Value>
                        <ValueType>STRING</ValueType>
                        <Children/>
                        </Attribute>
                        <Attribute>
                        <Name>Test1</Name>
                        <Value>TestVlau1</Value>
                        <ValueType>STRING</ValueType>
                        <Children/>
                        </Attribute>
                        </Attributes><XAttributes>";

        var attribute = attr.ToObject<XAttributes>();

私はエラーが発生します

There is an error in XML document (14, 55).

ラインで

 obj = s.Deserialize(sr);

どんな助けでも大歓迎です。

ありがとう。

4

1 に答える 1

0

ここに問題があるかどうかを判断するのは難しいですが、次のことを試してください。

[XmlTypeAttribute(TypeName="XAttributes")]
public class XAttributes 
{
    ....
}

これとともに:

[XmlRoot("XAttributes")]
public class XAttributes 
{
    ....
}

また、XML文字列にXML宣言を含めることを忘れないでください。

string attr = @"<?xml version="1.0" encoding="utf-8"?>
    <XAttributes><Attributes>                          
        <Attribute>
        <Name>Test</Name>
        <Value>TestVlau</Value>
        <ValueType>STRING</ValueType>
        <Children/>
        </Attribute>
        <Attribute>
        <Name>Test1</Name>
        <Value>TestVlau1</Value>
        <ValueType>STRING</ValueType>
        <Children/>
        </Attribute>
        </Attributes><XAttributes>";

PS:便利な汎用XmlSerializerを作成しました。CodeProjectの私の記事をご覧ください。

Genericsを使用したXMLシリアル化

于 2013-02-20T23:38:54.543 に答える