views:

357

answers:

1

There are a number of posts on here about merging XML with Java, but I can't seem to find any reference to Actionscript for the same task.

I have a group of XML files that I need to load. I want them to sort into one XML Object in memory.

For example, let's say these were my XML files:

File 1

<xml>
    <type name="1" group="a">
        <unit> value1 </unit>
    </type>
    <type name="1" group="b">
        <unit> value2 </unit>
    </type>
    <type name="2" group="a">
        <unit> value3 </unit>
    </type>
</xml>

File 2

<xml>
    <type name="1" group="a">
        <unit> value4 </unit>
    </type>
    <type name="1" group="b">
        <unit> value5 </unit>
    </type>
    <type name="2" group="a">
        <unit> value6 </unit>
    </type>
    <type name="3" group="a">
        <unit> value7 </unit>
    </type>
</xml>

Merged

<xml>
    <type name="1" group="a">
        <unit> value1 </unit>
        <unit> value4 </unit>
    </type>
    <type name="1" group="b">
        <unit> value2 </unit>
        <unit> value5 </unit>
    </type>
    <type name="2" group="a">
        <unit> value3 </unit>
        <unit> value6 </unit>
    </type>
    <type name="3" group="a">
        <unit> value7 </unit>
    </type>
</xml>

In this example, the two files are merged, and unit's are placed within like type names and groups.

Sorting priority: Type Name > Type Group > Unit Value

I hope that's clear. Please ask if additional clarification is necessary.

+1  A: 

This should work for the given example.

var t1:XML, t2:XML;
var merged:XML = new XML(file1.toXMLString())
for each(t1 in merged.type)
  for each(t2 in file2.type.(@name == t1.@name && @group == t1.@group))
    t1.appendChild(t2.unit.toXMLString());
for each(t2 in file2.type)
  if(merged.type.(@name == t2.@name && @group == t2.@group).length() == 0)
    merged.appendChild(t2.toXMLString());
trace(merged.toXMLString());
Amarghosh