Gero
Gero

Reputation: 13553

transform XML object with XSLT to already existing XML object with C#

I have an XML document deserialized (an object contains the data). Now I am using an XSLT transformation file to create a new XML document.

transform(myXmlSourceObject, XSLT, output);

The variable output is now a Stream, XmlWriter or a String. It contains the new xml structure defined by the XSLT.

But I want to replace output with my desired target xml object, which i have already created/deserialized from the schema of the target xml. That means that I already have an objects that will be the target of the transformation. No new Stream, XmlWriter or String.

TargetXml alreadyCreatedTargetXmlObject = new TargetXml();
transform(myXmlSourceObject, XSLT, alreadyCreatedTargetXmlObject);

The point is that I want to fill the alreadyCreatedTargetXmlObject with values from myXmlSourceObject but also be able to do edit fields like the following

alreadyCreatedTargetXmlObject.name ="SomeNewName";
alreadyCreatedTargetXmlObject.location.x="50.78";

The new xml would be filled with data, and I want to edit values if I need to.

Upvotes: 1

Views: 1012

Answers (2)

Petru Gardea
Petru Gardea

Reputation: 21638

You will have to implement this functionality yourself - at least when you're using the standard, built-in .NET XSLT API.

Since what you want is not a complicated exercise to achieve (assuming the transformation gives you always the same root element and you're using a deserializer that supports merge then it's more in the error handling rather than the actual code), I have to assume a concern here is performance. Intuitively, if you want XSLT as your language to transform, the only way around performance would be to build extensions - again an easy task on .NET - but that would reduce the portability of your XSLT.

Update (to address your comment):

(I am not sure I understand why you want to have the target object created before transformation.)

You can try to do this: set up a call to XslTransform.Transform to do your transformation into a Stream (as I said, you implement yourself "the illusion" - the way you want your API to look). Use protobuf's Serializer.Merge passing in an XmlReader from your stream above, and your pre-existing object to merge the two (for what reason, unclear). The type of the pre-existing object should've been generated using xsd.exe - I would think.

Based on the pseudo code you've provided, you can get away without the merge step. Just return the object you deserialize (generated using xsd.exe based on the target XML XSD) from the stream passed to the Transform and then set whatever properties you want - same thing.

Upvotes: 1

Eric S
Eric S

Reputation: 462

I may be wrong, but I'm not sure you could do that with XSLT. The simpliest way is probably to deserialize the output of the xslt after transformation, or writing the transform directly in Java to be able to access your objects.

Upvotes: 0

Related Questions