Groups | Blog | Home
all groups > dotnet xml > february 2005 >

dotnet xml : Changing a single value in an xml file


Brett
2/18/2005 7:33:04 AM
I often have to change a single value in an xml file based off of a given ID.
Is there any easy way to do this through .net.xml?
Martin Honnen
2/18/2005 5:09:26 PM


[quoted text, click to view]

Depending on what you are used to DOM is rather simple, if the attribute
is defined in the DTD and of type ID then all you need is
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(fileName);
XmlElement element = xmlDocument.GetElementById(id);
if (element != null) {
// change element content here, don't know from your post
// what exactly you want to change

// then save back
xmlDocument.Save(fileName);
}
With .NET even if the attribute is not of type ID you can easily use
XPath and SelectSingleNode to find a specific element instead of using
GetElementById.

Of course for large files building a DOM tree to change a single value
can be inefficient so depending on file size and memory constraints you
could also think about an XmlReader mirroring anything but that element
that you want to change.

Or you could use XML means of composing stuff and use an external entity
which the main file references, then you only need to change the
external entity and the main big file is not touched/parsed/loaded at all.

--

Martin Honnen
AddThis Social Bookmark Button