0

I would like to perform object serialization to only one branch in an existing XML file. While reading by using:

        RiskConfiguration AnObject;

        XmlSerializer Xml_Serializer = new XmlSerializer(typeof(RiskConfiguration));
        XmlTextReader XmlReader = new XmlTextReader(@"d:\Projects\RiskService\WCFRiskService\Web.config");
        XmlReader.ReadToDescendant("RiskConfiguration");
        try
        {
            AnObject = (RiskConfiguration)Xml_Serializer.Deserialize(XmlReader);
            AnObject.Databases.Database[0].name = "NewName";
        }
        finally
        {
            XmlReader.Close();
        }

It is possible, I do not know how to edit the object again performed it can save the file without erasing other existing elements in an XML file. Can anyone help me?

I found a way to display the desired item serialization. How do I go now instead of the paste to the original element in XML?

        StringWriter wr = new StringWriter();
        XmlWriterSettings settings = new XmlWriterSettings();
        settings.Indent = true;
        settings.OmitXmlDeclaration = true;
        settings.Encoding = System.Text.Encoding.Default;

        using (XmlWriter writer = XmlWriter.Create(wr, settings))
        {
            XmlSerializerNamespaces emptyNamespace = new XmlSerializerNamespaces();
            emptyNamespace.Add(String.Empty, String.Empty);
            Xml_Serializer.Serialize(writer, AnObject, emptyNamespace);
            MessageBox.Show(wr.ToString());
        }
Emil J
  • 215
  • 2
  • 4
  • 20
  • Does anything else access the xml file or is yours the only process that does anything with it? If not, you could maintain an XDocument or XmlDocument which holds the original XML and pull our the relevant parts you want to serialise/deserialise and flush it back to disk when you update the document. – Jay Feb 06 '13 at 14:56

1 Answers1

2

First of all, you should stop using new XmlTextReader(). That has been deprecated since .NET 2.0. Use XmlReader.Create() instead.

Second, XML is not a random-access medium. You can't move forward and backwards, writing into the middle of the file. It's a text-based file.

If you need to "modify" the file, then you'll need to write a new version of the file. You could read from the original file, up to the point where you need to deserialize, writing the nodes out to a new version of the file. You could then deserialize from the original file, modify the objects, and serialize out to the new version. You could then continue reading from the original and writing the nodes out to the new version.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
  • Ok. But how can I paste the serialized object instead of the original XML element, so that it did not contain the namespaces and xml header? – Emil J Feb 06 '13 at 15:03