尝试编写内部标记

时间:2016-07-28 23:43:48

标签: c# xml ixmlserializable

这是一个测试类:

    [XmlRoot("Test")]
    class Test : IXmlSerializable
    {
        public string Attr { get; set; }
        // ... more properties here...

        public XmlSchema GetSchema()
        {
            return null;
        }

        public void ReadXml(XmlReader reader)
        {
            throw new NotImplementedException();
        }

        public void WriteXml(XmlWriter writer)
        {
            writer.WriteAttributeString("attr", Attr);
            writer.WriteStartElement("InnerTest"); // <-- exception
            // ... write inner stuff 
            writer.WriteEndElement();
        }
    }

当我调用WriteXml时,会抛出异常:

Index was outside the bounds of the array.
   at System.Xml.XmlTextWriter.WriteEndStartTag(Boolean empty)
   at System.Xml.XmlTextWriter.AutoComplete(Token token)
   at System.Xml.XmlTextWriter.WriteStartElement(String prefix, String localName, String ns)
   at System.Xml.XmlWriter.WriteStartElement(String localName)
   at Tests.Test.WriteXml(XmlWriter writer) 

在互联网上的示例中,此代码不会导致任何问题(例如http://www.codeproject.com/Articles/43237/How-to-Implement-IXmlSerializable-Correctly),但对我来说它不起作用。可能是什么原因?

更新 最后,我希望这个类能够像这样序列化:

<Test attr="..."><InnerTest>...</InnerTest></Test>

1 个答案:

答案 0 :(得分:1)

我认为您的问题可能更多地是关于如何调用序列化程序而不是WriteXml代码的实现方式。例如在LINQPad中,我这样做了:

with agg(id, min_ind, max_ind, cnt) as (
    select id, min(ind), max(ind), count(*)
    from
        (
        select id, ind, val, sum(brk) over (partition by id order by ind desc) as grp
        from
            (
            select 
                id, ind, val,
                coalesce(sign(lag(ind) over (partition by id, val order by ind desc) - ind - 1), 1) as brk
            from myValues
            ) as d
        ) as d
    group by id, grp
)
select v.id, v.ind, v.val, a.cnt
from myValues v inner join agg a on a.id = v.id and v.ind between min_ind and max_ind
order by v.id, v.ind desc;

我收到了这个输出:

<Response [404]> 
{
    "error":{
        "code":"20102","message":"The specified resource ID does not exist.","@api.url":"http://aka.ms/onenote-errors#C20102" 
    }
}