Reputation:
I have one simple class:
public class A
{
public string Property { get; set; }
}
And I want when I serialize:
<NodeSurrounded>
<A>
<Property>value</Property>
</A>
</nodeSurrounded>
I am obliged to add an additional class to add the node NodeSurrounded?
Upvotes: 0
Views: 926
Reputation: 14251
Try following approach
A a = new A { Property = "value" };
var xs = new XmlSerializer(typeof(A));
using (var xmlWriter = XmlWriter.Create("test.xml"))
{
xmlWriter.WriteStartElement("NodeSurrounded");
xs.Serialize(xmlWriter, a);
xmlWriter.WriteEndElement();
}
We manually add the xml node.
Then, on deserialization, we also have to manually bypass this node.
using (var xmlReader = XmlReader.Create("test.xml"))
{
xmlReader.ReadToFollowing("A");
a = (A)xs.Deserialize(xmlReader);
}
Upvotes: 2
Reputation: 1687
I would create a ToXML()
and a FromXML()
methods inside your class.
public string ToXML()
{
return new XDocument(
new XElement("NodeSurrounded"),
new XElement("A", this.Property)).ToString();
}
public void FromXML(string xml)
{
var document = XDocument.Parse(xml);
this.Property = document.Root.Element("A").Element("Property").Value;
}
Upvotes: 0
Reputation: 1
You could create a new node. Then use XmlNode.AppendChild
to append to your NodeSurrounded node
Upvotes: 0