XML Transform

Status
Not open for further replies.
My brain is fried -- extra crispy -- and I'm not sure where to even look to how to do this.

I have been given the following construct:

Code:
<sequence>
  <sequence-item order="1" value-lookup="2" />
  <sequence-item order="2" value-lookup="3" />
  <sequence-item order="3" value-lookup="1" />
</sequence>

<ranges>
  <range>
    <min>10</min>
    <max>20</max>
  </range>
  <range>
    <min>15</min>
    <max>25</max>
  </range>
  <range>
    <min>30</min>
    <max>45</max>
  </range>
</ranges>

I need to 'in-line' the ranges with the sequence, as such:

Code:
<sequence>
  <sequence-item order="1">
    <range>
      <range-id>128</range-id>
      <min>15</min>
      <max>25</max>
    </range>
  </sequence-item
  <sequence-item order="2">
    <range>
      <range-id>244</range-id>
      <min>30</min>
      <max>45</max>
    </range>
  </sequence-item>
  <sequence-item order="3">
    <range>
      <range-id>542</range-id>
      <min>10</min>
      <max>20</max>
    </range>
  </sequence-item>
<sequence>

<ranges>
  <range>
    <range-id>128</range-id>
    <min>10</min>
    <max>20</max>
  </range>
  <range>
    <range-id>244</range-id>
    <min>15</min>
    <max>25</max>
  </range>
  <range>
    <range-id>542</range-id>
    <min>30</min>
    <max>45</max>
  </range>
</ranges>

So I need to:

  • grab the value-lookup number, n
  • go to the nth item, positionally, in the ranges 'list' and
  • copy that nth range item into the sequence

I don't know where to start to do this. I'm sure using something like /ranges[position()=$sequence-item@value-lookup] ... but I keep getting garbage when I try something this simple ... and I don't know how to copy the whole 'range' item.

Also, to make things even harder, I need to add a GUID-based range-id field to each range item, and maintain that between the copies. I know how to add the new -id bit and the GUID ... pretty simple stuff.

Can this be done fairly easily in one-pass, or should I run in two passes, first with the GUID insertion, then do the copy translation?

No, this isn't homework ... I'm back on this project that was bumped due to higher priorities.

XML is hard ... :p
 
fitten":1zd4r9go said:
That's XSLT ;) XML isn't hard unless you get off into the wildness of namespaces and all that stuff, IMO ;) If you can do HTML, you're most of the way there with basic XML.

Fair enough ... but ... what does the 'X' in XSLT stand for again? :)

Argh ... this is twisting my brain ... I don't know why either ... this stuff should be pretty straight-forward.

I've got the range-id injecting (weird magical numbers depending on the transformation engine, but I don't care at this point).
Code:
<xsl:template match="ranges/range">
  <xsl:copy>
    <!-- inject the id -->
    <xsl:element name="range-id">
      <xsl:value-of select="generate-id()" />
    </xsl:element>
    <!-- copy remaining bits -->
    <xsl:apply-templates select="@* | node()" />
  </xsl:copy>
</xsl:template>

Now to figure a way to inject that same number into the sequence-item's value-lookup attribute ...
 

fitten

Ars Legatus Legionis
55,634
Subscriptor++
zelmak":2s14p7vk said:
fitten":2s14p7vk said:
I actually don't do a lot of XSLT (have done some). I usually find it much easier to just write a little app that does it (using XPath and such).

Well, it is my understanding that XSLT uses XPath notation to do its magic ... how would you do it in an XPath? :wink:

Yes, it does but the syntax of XSLT can be a little hard to get right. However, where XPath queries are used to get what you want and then something like C# (or whatever your favorite language is that you're more familiar with) syntax is used to do the manipulations, it's less confusing. A C# program to do what you describe above is easily less than 50 lines and not at all hard to write, IMO (because C# is easier to me than XSLT).
 

fitten

Ars Legatus Legionis
55,634
Subscriptor++
Assuming your sequences and ranges are in separate files (since they have to be given your XML), this extremely quick and dirty code will produce your output given above (and I wrote and tested it in the 20 minutes between these two posts ;) I had to actually decide whether or not to even do it in that time, too ;) ):

Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.XPath;

namespace XmlProc
{
    class Program
    {
        static void Main(string[] args)
        {
            XmlDocument seqDoc = new XmlDocument();
            seqDoc.Load("sequence.xml");
            XmlDocument dataDoc = new XmlDocument();
            dataDoc.Load("data.xml");
            Process(seqDoc.CreateNavigator(), dataDoc.CreateNavigator());
            Console.WriteLine("Done");
        }
        static void Process(XPathNavigator seqNav, XPathNavigator dataNav)
        {
            foreach (XPathNavigator seq in seqNav.Select("/sequence/sequence-item"))
            {
                XPathNavigator an = seq.SelectSingleNode("./@value-lookup");
                string query = string.Format("/ranges/range[position() = {0}]", an.Value);
                XPathNavigator ni = dataNav.SelectSingleNode(query);
                if (ni != null)
                    seq.InnerXml += ni.OuterXml;
                an.DeleteSelf();
            }
        }
    }
}

Edit: made the above a tiny bit less embarrassing ;)
 

Caelestian

Ars Centurion
236
Subscriptor++
Code:
<xsl:stylesheet version="1.0" 
	xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
	
<xsl:template match="/">
	<xsl:apply-templates select="//sequence" />
</xsl:template>

<xsl:template match="sequence">
	<sequence>
		<xsl:for-each select="sequence-item">
			<xsl:sort select="@order" />
			<xsl:apply-templates select="." />
		</xsl:for-each>
	</sequence>
</xsl:template>

<xsl:template match="sequence-item" >
	<xsl:variable name="lookupPosition" select="@value-lookup" />
	<sequence-item order="{@order}" >
		<xsl:apply-templates select="//ranges/range[position() = $lookupPosition]"/>
	</sequence-item>
</xsl:template>

<xsl:template match="range">
<range>
	<range-id><xsl:value-of select="generate-id()" /></range-id>
	<xsl:copy-of select="min"/>
	<xsl:copy-of select="max"/>
</range>
</xsl:template>

</xsl:stylesheet>
 
Caelestian":2eic04op said:
Code:
<xsl:stylesheet version="1.0" 
	xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
	
<xsl:template match="/">
	<xsl:apply-templates select="//sequence" />
</xsl:template>

<xsl:template match="sequence">
	<sequence>
		<xsl:for-each select="sequence-item">
			<xsl:sort select="@order" />
			<xsl:apply-templates select="." />
		</xsl:for-each>
	</sequence>
</xsl:template>

<xsl:template match="sequence-item" >
	<xsl:variable name="lookupPosition" select="@value-lookup" />
	<sequence-item order="{@order}" >
		<xsl:apply-templates select="//ranges/range[position() = $lookupPosition]"/>
	</sequence-item>
</xsl:template>

<xsl:template match="range">
<range>
	<range-id><xsl:value-of select="generate-id()" /></range-id>
	<xsl:copy-of select="min"/>
	<xsl:copy-of select="max"/>
</range>
</xsl:template>

</xsl:stylesheet>

Thanks Caelestian!!

Dangit, that looks like it should work, but the 'range' template never seems to fire. I'll futz with this to see if I can get it to work.
 
Okay, so, I got what I asked for ... and after trying to work with it, I'm finding that it's not what I need.

Instead of in-lining everything, I just want to create the new GUID for each 'range', and copy it in place of the sequence-item value-lookup attribute.

Like:
Code:
<sequence>
  <sequence-item order="1" value-lookup="13" />
  <sequence-item order="2" value-lookup="14" />
  <sequence-item order="3" value-lookup="12" />
</sequence>

<ranges>
  <range index="12">
    <min>10</min>
    <max>20</max>
  </range>
  <range index="13">
    <min>15</min>
    <max>25</max>
  </range>
  <range index="14">
    <min>30</min>
    <max>45</max>
  </range>
</ranges>

Whether it's an attribute or an element doesn't really seem to matter at this point.

I've been futzing with what you gave me to try to achieve the desired results, but I can't simply pick up the attribute without grabbing the whole range. I don't know why I'm having such a hard time wrapping my brain around this transformation stuff (although, it does feel like functional programming, which I don't really get, either.)

Perhaps I *should* write a program to do this, but this is one substructure of a larger XML structure. I want to pass the rest of it through unscathed and only modify this one bit -- an identity transform with only the ranges/range and sequence/sequence-item bits are changed seems quite easy.

Any (further) help would be most appreciated.
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
If you write a simple XmlReader loop, maintain whatever state you need and by default write out everything coming at you (including comments and the like) except where you know you need to change things it may end up being pretty simple.

You basically write the state machine, so long as the state and the machine bits are not too complex the result is pretty easy to follow and work with (you just have to know when to stop and revisit if changing requirements keep creeping in over time)
 

Raqem

Ars Tribunus Angusticlavius
7,586
I'm new to XPath, and I'm not 100% sure I understand what your goal is. However, in regards to:

zelmak":15s27vaq said:
...but I can't simply pick up the attribute without grabbing the whole range.

If I'm understanding what you're saying here, then you want to use this XPath (based on Caelestian's XSLT):

Code:
//ranges/range[position() = $lookupPosition]/@index

In any case, I'm interested in this thought exercise. Is your initially posted XML still the before and this latest posted XML the after?
 
Raqem":uh9rv198 said:
I'm new to XPath,

me too :) :facepalm:

and I'm not 100% sure I understand what your goal is. However, in regards to:

zelmak":uh9rv198 said:
...but I can't simply pick up the attribute without grabbing the whole range.

If I'm understanding what you're saying here, then you want to use this XPath (based on Caelestian's XSLT):

Code:
//ranges/range[position() = $lookupPosition]/@index

The version cael gave me did precisely what I asked ... it inlined a whole copy of the selected range element into the sequence-item element. I can't seem to make the processor downstream work with this. Now, I want to try it simply with the indices, to see if I can make it work with less duplicatoin.

Thanks. I'll try yours ... It should have been obvious to me, but this whole thing has got me flustered and frustrated and I'm not thinking straight.

In any case, I'm interested in this thought exercise. Is your initially posted XML still the before and this latest posted XML the after?

They're both snippets and sanitized versions of what I want to do, not the actual thing I'm working on, so yes and at the same time, no. I reckon if you wrap both parts in a <data></data> element, it would be legal XML for a one file solution...

Ultimately, I'm trying to import a XML-based heirarchical dump of a 'database' into a C#-based program that can use a JAXB-generated Java library (.jar) to parse the provided XML. Of course, in that C# program, there are a minimum of 5 XML configuration files which need to be updated to make this happen for every field that needs to be rendered:
(a) Object Mapping - Creating named objects from xpath-like structure definitions
(b) Logical Layout - Grouping like objects from (a)
(c) Physical Layout - database tables, fields
(d) On-screen Layout - Which logical 'fields' of which logical 'tables' get shown on screen (one of these per on-screen grouping)
(e) Relationships - Recreates the heirarchy of parent to child records

I have no API for the C# program. I don't have Visual Studio nor the source (although both are available -- they want me to not change source to make this all work, just manipulate the mapping files, above.)

So everything I'm doing, which includes modifying the XML schema to match the changes I'm making to the XML structure, is all being reverse-engineered based on what I see in the current XML layout files and observation of the running program (which further exacerbates my code/build/test cycle because it takes about five minutes to show up on-screen so that I can even see if I've made a dent.) And it is tiring.

Sorry, I'm venting a bit, but there seemed to be concern as to what I am working with and why.

<mode rant="off">
 
Raqem":3ea2i9hi said:
I'm new to XPath, and I'm not 100% sure I understand what your goal is. However, in regards to:

zelmak":3ea2i9hi said:
...but I can't simply pick up the attribute without grabbing the whole range.

If I'm understanding what you're saying here, then you want to use this XPath (based on Caelestian's XSLT):

Code:
//ranges/range[position() = $lookupPosition]/@index

In any case, I'm interested in this thought exercise. Is your initially posted XML still the before and this latest posted XML the after?

Alas, no this doesn't seem to work. Something about the copy vs. direct access hides the new GUID value... it shows up when you copy the whole element (Cael's version).
 
Status
Not open for further replies.