TruMan1
TruMan1

Reputation: 36068

How to check if XmlDocument has changed?

I am conditionally changing an XmlDocument in various parts of my code. Instead of passing a "changed" flag around, does the XmlDocument object have something built flag for this (like isDirty)?

var doc = new XmlDocument();
doc.Load(file);

if (...) parent.AppendChild(element);
if (...) parent2.AppendChild(element2);
if (...) parent3.AppendChild(element3);

//METHOD DOESN'T EXIST
if (doc.isDirty())
  doc.Save(file);

Upvotes: 2

Views: 2279

Answers (2)

Ruben
Ruben

Reputation: 15505

Although an XmlDocument does not expose an IsDirty flag, it does have events like NodeChanged, NodeInserted and NodeRemoved which you could use to keep a single flag, which you do not need to pass to any mutation methods:

var doc = new XmlDocument();
doc.Load(file);

bool changed = false;

XmlNodeChangedEventHandler handler = (sender, e) => changed = true;
doc.NodeChanged += handler;
doc.NodeInserted += handler;
doc.NodeRemoved += handler;

// do some work

if (changed)
    doc.Save(file);

Upvotes: 5

Kieren Johnstone
Kieren Johnstone

Reputation: 41983

No, XmlDocument stores a document, it does not track changes. Wrap it in a helper class, set a flag as you describe, or create some other OO structure to work the way you want.

Upvotes: 2

Related Questions