简体   繁体   English

使用LINQ to XML实现IXmlSerializable

[英]Using LINQ to XML to implement IXmlSerializable

I feel like this is probably a duplicate, but I can't find the exact answer I'm looking for. 我觉得这可能是重复的,但我找不到我正在寻找的确切答案。 I am implementing IXmlSerializable on an object and want to know if it would be acceptable to use linq-to-xml . 我正在对象上实现IXmlSerializable ,并想知道使用linq-to-xml是否可以接受。

Replace this... 替换这个......

public void WriteXml(XmlWriter writer)
{
    writer.WriteElementString("Name", _name);
    writer.WriteElementString("X", _x.ToString());
    writer.WriteElementString("Y", _y.ToString());
}

with this... 有了这个...

public void WriteXml(XmlWriter writer)
{
    XElement element =
        new XElement("MyObj",
            new XElement("Name", _name),
            new Xelement("X", _x),
            new Xelement("Y", _y)
        );

    element.WriteTo(writer);
}

My actual implementation is obviously more complex to the point that I feel the linq-to-xml structure is simpler and more readable. 我的实际实现显然更复杂,我认为linq-to-xml结构更简单,更易读。 Is the above acceptable? 以上是否可以接受?

The first implementation doesn't generate the same xml as the second one. 第一个实现不会生成与第二个相同的xml。 You should write the second implementation as follows to match the xml generated by the first one: 您应该编写第二个实现,如下所示,以匹配第一个生成的xml:

public void WriteXml(XmlWriter writer)
{
    new XElement("Name", _name).WriteTo(writer);
    new XElement("X", _x).WriteTo(writer);
    new XElement("Y", _y).WriteTo(writer);
}

Besides, when you call 此外,当你打电话

writer.WriteElementString("X", _x.ToString());

the result could be non XML-compliant and vulnerable to incorrect parsing, depending on _x type (for example, if type of _x is DateTime), so the second implementation is better, at least in this regard. 结果可能是非XML兼容的,并且容易受到错误的解析,这取决于_x类型(例如,如果_x的类型是DateTime),所以第二个实现更好,至少在这方面。

I got some of this info from C# 5 in a Nutshell. 我在Nutshell中从C#5获得了一些这些信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM