How do I model a dynamic XML element in a C# serialization class?

霸气de小男生 提交于 2019-12-10 12:09:52

问题


I have an XML document where one of the element nodes can be dynamic, or of any XML structure. I'm having a difficult time modeling the corresponding C# serialization class.

For example I have something like this in my C# class:

[XmlAnyElement]
public XmlNode Value { get; set; }

Where XmlNode is System.Xml.XmlNode.

A few notes:

  • I want value to be an XML file I'm loading via Linq's XDocument (minus the XML header tag)
    • Though I don't see a way to convert an System.Xml.Linq.XNode to System.Xml.XmlNode
  • I don't want the result XML to have an element <Value>. I want it to be the root element of the XML document I loaded.

回答1:


I figured this out. I kept the property declaration the same and created this helper class:


public static class XmlDocumentHelper
{
    public static XmlDocument FromXDocument(XDocument document)
    {
        var result = new XmlDocument();
        using (XmlReader reader = document.CreateReader())
        {
            result.Load(reader);
        }
        return result;
    }
}

So Value is set like this: Value = XmlDocumentHelper.FromXDocument(document);



来源:https://stackoverflow.com/questions/3558659/how-do-i-model-a-dynamic-xml-element-in-a-c-sharp-serialization-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!