Home > Blockchain >  XML: How do you change/group XML based on an attribute?
XML: How do you change/group XML based on an attribute?

Time:05-05

I'm brand new to XML so I have a question about how to manipulate XML data. My current data has an EmployeeID in 2 different segments (not sure of terminology here, maybe attribute). I want to combine the segments per EmployeeID and ensure all data for an EmployeeID is in one segment.

I'm not asking anyone to solve this for me, but to give me options on how this can be accomplished.

Does this type of transformation typically happen in a programming language like C#, or is there another way to get the XML data transformed? So new to it, not sure what the next step would be.

Current Data:

 <Employees>
  <Employee>
    <EmployeeID>9999999999</EmployeeID>
    <DaysOfWeekShort></DaysOfWeekShort>
    <TimeOfDay>AM</TimeOfDay>
    <BusNumber>7777      </BusNumber>
  </Employee>
  <Employee>
    <EmployeeID>9999999999</EmployeeID>
    <DaysOfWeekShort></DaysOfWeekShort>
    <TimeOfDay>PM</TimeOfDay>
    <BusNumber>8888      </BusNumber>
  </Employee>
</Employees>

Desired Result:

<Employees>
  <Employee>
    <EmployeeID>9999999999</EmployeeID>
      <DaysOfWeekShort></DaysOfWeekShort>
        <TimeOfDay>AM</TimeOfDay>
          <BusNumber>7777      </BusNumber>
        <TimeOfDay>PM</TimeOfDay>
          <BusNumber>8888      </BusNumber>
  </Employee>
</Employees>

CodePudding user response:

Does this type of transformation typically happen in a programming language like C# ...

Fundamentally, yes. XML is just a data format, it doesn't have "behaviour" as such. Just like you need some kind of program to change the colours of an image, you need some kind of program to change the order of elements in an XML document.

... or is there another way to get the XML data transformed?

Just as there are specialist tools for working with images, there are specialist tools for working with XML. For instance, there is a language called "XSLT" whose sole purpose is to transform the data in an XML document.

CodePudding user response:

You can do this transformation in a general-purpose programming language, or you can do it in XSLT, which was designed specifically for this job.

In XSLT (version 3.0) this might look like

<xsl:template match="Employees">
  <xsl:for-each-group select="*" group-by="EmployeeID">
    <Employee>
      <xsl:copy-of select="EmployeeID, DaysOfWeekShort"/>
      <xsl:copy-of select="current-group()!(TimeOfDay, BusNumber)"/>
    </Employee>
  </xsl:for-each-group>
</xsl:template>

The XSLT solution will usually be much shorter (and therefore easier to change), but of course it's another technology to learn. The basic idea is that you define a set of transformation rules, each of which has a match pattern to say what part of the input it is matching, and a template body to construct the corresponding output.

  •  Tags:  
  • xml
  • Related