user6313890
user6313890

Reputation:

Add node in serialization

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

Answers (3)

Alexander Petrov
Alexander Petrov

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

C1rdec
C1rdec

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

Joshua Davis
Joshua Davis

Reputation: 1

You could create a new node. Then use XmlNode.AppendChild

to append to your NodeSurrounded node

Upvotes: 0

Related Questions