views:

36

answers:

2

My requirement is to update an XML file (some elements identified via a parameter, with new attribute values again identified via a paramenter).

I am using XSLT to do the same via C# code.

My code is as below:

XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load(f_Xslt);
XmlReader xr = XmlReader.Create("SourceXML.xml");
XmlWriter xw = XmlWriter.Create("DestinationXML.xml");
XsltArgumentList argsList = new XsltArgumentList(); 
argsList.AddParam("", "", "");
...
...
...
xslt.Transform(xr, argsList, xw);

In my XSLT file, I first copy all elements, attributes. And then based on <xsl:template match = ... />, I update the elements, attr/values.

All this is saved to Destination.xml

What if I want all of this to happen on Source.xml itself.

Of course, the easiest solution(or my solution so far) is to replace the Source.XML with Destination.XML after I complete the XSLT.Transform successfully.

+1  A: 

I think your transform-to-file-then-replace solution is as good as you're going to get. You don't want to overwrite the Source.XML file while reading it, even if .NET and the OS would let you.

In order to suggest a better alternative to transform-to-file-then-replace (TTFTR), I would ask, what is it about TTFTR that you feel is suboptimal?

The only alternative I can think of off-hand is to write the result of your transform to memory; and when the transform is finished, save the result from memory onto your source file. To transform to memory, pass a MemoryStream object as the argument to XmlWriter.Create().

LarsH
+1  A: 

You never should try to update in-place with XSLT. This is bad design and not in the spirit of a functional language.

This said, you can copy the source XML file in a temporary directory, then apply the transformation with an XmlWriter instance that is created to overwrite the original file.

As I said before, I wouldn't recommend this!

Dimitre Novatchev