问题
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