简体   繁体   中英

Transform an XML node value using XSLT

General Description of the Problem

I have several XMLs coming from different sources and I'm using XSLT to transform them into one standard format that a C# application can parse uniformly. I have already a proof-of-concept transformation already working, and I'm able to transform an XHTML (almost) completely into my standard XML. This question is about that "almost".

The C# application expects that the input xml (the output of the transformation) complies to a format, not only in the structure of the xml elements but also in the format of the data inside the nodes, for example, a <date> element must be in the format of "yyyy/MM/dd" , however one input xml (for the transformation) can come in a dd/MM format while another is the way around.

Note that I control the C# application and designed the standard XML template, so changing any of these isn't an issue, I also know the exact format of the different incoming XMLs to be transformed, and I'm developing one transformation for each type of XML I receive, because they can be greatly different from each other and I wouldn't want that by changing the transformation to fit a change in a format I break another that was previously working.

Specific Question about my Problem

So, cutting to the chase, how can I transform the value of the nodes using XLST? How can I tell the transformation to take this node value from (especifically) dd/MM format, and transform it into yyyy/MM/dd ?

PS I have considered creating an extra XML for configuration so that I can to this type of transformation, for every format, inside C#, however I'd like this to be a last resource. I'd like it so that the output of the XSLT is 100% standard. I have also found some other SO questions describing the process of transforming values, but all of these talk about conditional replacement, seeing if the value equals x and outputting y , that wouldn't do it because dates can be anything.

How can I tell the transformation to take this node value from (especifically) dd/MM format, and transform it into yyyy/MM/dd?

Transforming a date from dd/mm/yyyy to yyyy/mm/dd is a relatively simple string manipulation:

<xsl:value-of select="concat(substring($node, 7, 4), '/', substring($node, 4, 2), '/', substring($node, 1, 2))"/>

Transforming a date from dd/mm to yyyy/mm/dd is not possible unless you add a rule regarding the year to add.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM