如何使用对以前标记的引用以及与某些类的子类型对应的子类解析xml?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (42)

我必须处理(以下情况的变化)。我的模型类是:

class Car {
    String brand;
    Engine engine;
}

abstract class Engine {
}

class V12Engine extends Engine {
    int horsePowers;
}

class V6Engine extends Engine {
    String fuelType;
}

我不得不反序列化(不需要序列化支持ATM)以下输入:

<list>

    <brand id="1">
        Volvo
    </brand>

    <car>
        <brand>BMW</brand>
        <v12engine horsePowers="300" />
    </car>

    <car>
        <brand refId="1" />
        <v6engine fuel="unleaded" />
    </car>

</list>

我尝试过的/问题:

我尝试过使用XStream,但它希望我编写如下标记:

<engine class="cars.V12Engine">
    <horsePowers>300</horsePowers>
</engine>

提问于
用户回答回答于

<list xmlns="http://example.com/cars">

    <brand id="1">
        Volvo
    </brand>

    <car>
        <brand>BMW</brand>
        <v12engine horsePowers="300" />
    </car>

    <car>
        <brand refId="1" />
        <v6engine fuel="unleaded" />
    </car>

</list>

并假设package-info.java

@XmlSchema(namespace = "http://example.com/cars",
           elementFormDefault = XmlNsForm.QUALIFIED)
package cars;
import javax.xml.bind.annotation.*;

引擎类型按元素名称使用@XmlElementRef:

package cars;
import javax.xml.bind.annotation.*;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Car {
    String brand;
    @XmlElementRef
    Engine engine;
}

@XmlRootElement
abstract class Engine {
}

@XmlRootElement(name = "v12engine")
@XmlAccessorType(XmlAccessType.FIELD)
class V12Engine extends Engine {
    @XmlAttribute
    int horsePowers;
}

@XmlRootElement(name = "v6engine")
@XmlAccessorType(XmlAccessType.FIELD)
class V6Engine extends Engine {
    // override the default attribute name, which would be fuelType
    @XmlAttribute(name = "fuel")
    String fuelType;
}

各种类型的Engine都有注解@XmlRootElement并用适当的元素名称标记。在解编组时,xml中找到的元素名称用于决定Engine要使用的子类。因此,给定

<car xmlns="http://example.com/cars">
    <brand>BMW</brand>
    <v12engine horsePowers="300" />
</car>

和解编组代码

JAXBContext ctx = JAXBContext.newInstance(Car.class, V6Engine.class, V12Engine.class);
Unmarshaller um = ctx.createUnmarshaller();
Car c = (Car)um.unmarshal(new File("file.xml"));

assert "BMW".equals(c.brand);
assert c.engine instanceof V12Engine;
assert ((V12Engine)c.engine).horsePowers == 300;

若要添加新类型的Engine只需创建新的子类,用@XmlRootElement,并将此新类添加到传递给JAXBContext.newInstance()第一步是定义一个JAXB类来表示<brand>

package cars;

import javax.xml.bind.annotation.*;

@XmlRootElement
public class Brand {
  @XmlValue // i.e. the simple content of the <brand> element
  String name;

  // optional id and refId attributes (optional because they're
  // Integer rather than int)
  @XmlAttribute
  Integer id;

  @XmlAttribute
  Integer refId;
}

现在我们需要一个“类型适配器”来在Brand对象和String要求Car,并维护id/ref映射。

package cars;

import javax.xml.bind.annotation.adapters.*;
import java.util.*;

public class BrandAdapter extends XmlAdapter<Brand, String> {
  private Map<Integer, Brand> brandCache = new HashMap<Integer, Brand>();

  public Brand marshal(String s) {
    return null;
  }


  public String unmarshal(Brand b) {
    if(b.id != null) {
      // this is a <brand id="..."> - cache it
      brandCache.put(b.id, b);
    }
    if(b.refId != null) {
      // this is a <brand refId="..."> - pull it from the cache
      b = brandCache.get(b.refId);
    }

    // and extract the name
    return (b.name == null) ? null : b.name.trim();
  }
}

我们将适配器链接到brand领域Car使用另一个注释:

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Car {
    @XmlJavaTypeAdapter(BrandAdapter.class)
    String brand;
    @XmlElementRef
    Engine engine;
}

谜题的最后一部分是确保<brand>在顶层找到的元素保存在缓存中。下面是一个完整的例子

package cars;

import javax.xml.bind.*;
import java.io.File;
import java.util.*;

import javax.xml.stream.*;
import javax.xml.transform.stream.StreamSource;

public class Main {
  public static void main(String[] argv) throws Exception {
    List<Car> cars = new ArayList<Car>();

    JAXBContext ctx = JAXBContext.newInstance(Car.class, V12Engine.class, V6Engine.class, Brand.class);
    Unmarshaller um = ctx.createUnmarshaller();

    // create an adapter, and register it with the unmarshaller
    BrandAdapter ba = new BrandAdapter();
    um.setAdapter(BrandAdapter.class, ba);

    // create a StAX XMLStreamReader to read the XML file
    XMLInputFactory xif = XMLInputFactory.newFactory();
    XMLStreamReader xsr = xif.createXMLStreamReader(new StreamSource(new File("file.xml")));

    xsr.nextTag(); // root <list> element
    xsr.nextTag(); // first <brand> or <car> child

    // read each <brand>/<car> in turn
    while(xsr.getEventType() == XMLStreamConstants.START_ELEMENT) {
      Object obj = um.unmarshal(xsr);

      // unmarshal from an XMLStreamReader leaves the reader pointing at
      // the event *after* the closing tag of the element we read.  If there
      // was a text node between the closing tag of this element and the opening
      // tag of the next then we will need to skip it.
      if(xsr.getEventType() != XMLStreamConstants.START_ELEMENT && xsr.getEventType() != XMLStreamConstants.END_ELEMENT) xsr.nextTag();

      if(obj instanceof Brand) {
        // top-level <brand> - hand it to the BrandAdapter so it can be
        // cached if necessary
        ba.unmarshal((Brand)obj);
      }
      if(obj instanceof Car) {
        cars.add((Car)obj);
      }
    }
    xsr.close();

    // at this point, cars contains all the Car objects we found, with
    // any <brand> refIds resolved.
  }
}
用户回答回答于

import com.thoughtworks.xstream.XStream
import com.thoughtworks.xstream.annotations.*
import com.thoughtworks.xstream.converters.*
import com.thoughtworks.xstream.converters.extended.ToAttributedValueConverter
import com.thoughtworks.xstream.io.*
import com.thoughtworks.xstream.mapper.Mapper

// The classes as given, plus toString()'s for readable output and XStream
// annotations to support unmarshalling. Note that with XStream's flexibility,
// all of this is possible with no annotations, so no code modifications are
// actually required.

@XStreamAlias("car")
// A custom converter for handling the oddities of parsing a Car, defined
// below.
@XStreamConverter(CarConverter)
class Car {
    String brand
    Engine engine
    String toString() { "Car{brand='$brand', engine=$engine}" }
}

abstract class Engine {
}

@XStreamAlias("v12engine")
class V12Engine extends Engine {
    @XStreamAsAttribute int horsePowers
    String toString() { "V12Engine{horsePowers=$horsePowers}" }
}

@XStreamAlias("v6engine")
class V6Engine extends Engine {
    @XStreamAsAttribute @XStreamAlias("fuel") String fuelType
    String toString() { "V6Engine{fuelType='$fuelType'}" }
}

// The given input:
String xml = """\
    <list>
        <brand id="1">
            Volvo
        </brand>
        <car>
            <brand>BMW</brand>
            <v12engine horsePowers="300" />
        </car>
        <car>
            <brand refId="1" />
            <v6engine fuel="unleaded" />
        </car>
    </list>"""

// The solution:

// A temporary Brand class to hold the relevant information needed for parsing
@XStreamAlias("brand")
// An out-of-the-box converter that uses a single field as the value of an
// element and makes everything else attributes: a perfect match for the given
// "brand" XML.
@XStreamConverter(value=ToAttributedValueConverter, strings="name")
class Brand {
    Integer id
    Integer refId
    String name
    String toString() { "Brand{id=$id, refId=$refId, name='$name'}" }
}

// Reads Car instances, figuring out the engine type and storing appropriate
// brand info along the way.
class CarConverter implements Converter {
    Mapper mapper

    // A Mapper can be injected auto-magically by XStream when converters are
    // configured via annotation.
    CarConverter(Mapper mapper) {
        this.mapper = mapper
    }

    Object unmarshal(HierarchicalStreamReader reader,
                     UnmarshallingContext context) {
        Car car = new Car()
        reader.moveDown()
        Brand brand = context.convertAnother(car, Brand)
        reader.moveUp()
        reader.moveDown()
        // The mapper knows about registered aliases and can tell us which
        // engine type it is.
        Class engineClass = mapper.realClass(reader.getNodeName())
        def engine = context.convertAnother(car, engineClass)
        reader.moveUp()
        // Set the brand name if available or a placeholder for later 
        // reference if not.
        if (brand.name) {
            car.brand = brand.name
        } else {
            car.brand = "#{$brand.refId}"
        }
        car.engine = engine
        return car
    }

    boolean canConvert(Class type) { type == Car }

    void marshal(Object source, HierarchicalStreamWriter writer,
                 MarshallingContext context) {
        throw new UnsupportedOperationException("Don't need this right now")
    }
}

// Now exercise it:

def x = new XStream()
// As written, this line would have to be modified to add new engine types,
// but if this isn't desirable, classpath scanning or some other kind of
// auto-registration could be set up, but not through XStream that I know of.
x.processAnnotations([Car, Brand, V12Engine, V6Engine] as Class[])
// Parsing will create a List containing Brands and Cars
def brandsAndCars = x.fromXML(xml)
List<Brand> brands = brandsAndCars.findAll { it instanceof Brand }
// XStream doesn't trim whitespace as occurs in the sample XML. Maybe it can
// be made to?
brands.each { it.name = it.name.trim() }
Map<Integer, Brand> brandsById = brands.collectEntries{ [it.id, it] }
List<Car> cars = brandsAndCars.findAll{ it instanceof Car }
// Regex match brand references and replace them with brand names.
cars.each {
    def brandReference = it.brand =~ /#\{(.*)\}/
    if (brandReference) {
        int brandId = brandReference[0][1].toInteger()
        it.brand = brandsById.get(brandId).name
    }
}
println "Brands:"
brands.each{ println "  $it" }
println "Cars:"
cars.each{ println "  $it" }

输出

Brands:
  Brand{id=1, refId=null, name='Volvo'}
Cars:
  Car{brand='BMW', engine=V12Engine{horsePowers=300}}
  Car{brand='Volvo', engine=V6Engine{fuelType='unleaded'}}

无注释的方法如下:

import com.thoughtworks.xstream.XStream
import com.thoughtworks.xstream.converters.*
import com.thoughtworks.xstream.converters.extended.ToAttributedValueConverter
import com.thoughtworks.xstream.io.*
import com.thoughtworks.xstream.mapper.Mapper

class Car {
    String brand
    Engine engine
    String toString() { "Car{brand='$brand', engine=$engine}" }
}

abstract class Engine {
}

class V12Engine extends Engine {
    int horsePowers
    String toString() { "V12Engine{horsePowers=$horsePowers}" }
}

class V6Engine extends Engine {
    String fuelType
    String toString() { "V6Engine{fuelType='$fuelType'}" }
}

String xml = """\
    <list>
        <brand id="1">
            Volvo
        </brand>
        <car>
            <brand>BMW</brand>
            <v12engine horsePowers="300" />
        </car>
        <car>
            <brand refId="1" />
            <v6engine fuel="unleaded" />
        </car>
    </list>"""

class Brand {
    Integer id
    Integer refId
    String name
    String toString() { "Brand{id=$id, refId=$refId, name='$name'}" }
}

class CarConverter implements Converter {
    Mapper mapper

    CarConverter(Mapper mapper) {
        this.mapper = mapper
    }

    Object unmarshal(HierarchicalStreamReader reader,
                     UnmarshallingContext context) {
        Car car = new Car()
        reader.moveDown()
        Brand brand = context.convertAnother(car, Brand)
        reader.moveUp()
        reader.moveDown()
        Class engineClass = mapper.realClass(reader.getNodeName())
        def engine = context.convertAnother(car, engineClass)
        reader.moveUp()
        if (brand.name) {
            car.brand = brand.name
        } else {
            car.brand = "#{$brand.refId}"
        }
        car.engine = engine
        return car
    }

    boolean canConvert(Class type) { type == Car }

    void marshal(Object source, HierarchicalStreamWriter writer,
                 MarshallingContext context) {
        throw new UnsupportedOperationException("Don't need this right now")
    }
}

def x = new XStream()
x.alias('car', Car)
x.alias('brand', Brand)
x.alias('v6engine', V6Engine)
x.alias('v12engine', V12Engine)
x.registerConverter(new CarConverter(x.mapper))
x.registerConverter(new ToAttributedValueConverter(Brand, x.mapper, x.reflectionProvider, x.converterLookup, 'name'))
x.useAttributeFor(V12Engine, 'horsePowers')
x.aliasAttribute(V6Engine, 'fuelType', 'fuel')
x.useAttributeFor(V6Engine, 'fuelType')
def brandsAndCars = x.fromXML(xml)
List<Brand> brands = brandsAndCars.findAll { it instanceof Brand }
brands.each { it.name = it.name.trim() }
Map<Integer, Brand> brandsById = brands.collectEntries{ [it.id, it] }
List<Car> cars = brandsAndCars.findAll{ it instanceof Car }
cars.each {
    def brandReference = it.brand =~ /#\{(.*)\}/
    if (brandReference) {
        int brandId = brandReference[0][1].toInteger()
        it.brand = brandsById.get(brandId).name
    }
}
println "Brands:"
brands.each{ println "  $it" }
println "Cars:"
cars.each{ println "  $it" }

如果你安装了Gradle,你可以把它放到一个build.gradle和上面的一个脚本src/main/groovy/XStreamExample.groovy,然后gradle run它将看到结果:

apply plugin: 'groovy'
apply plugin: 'application'

mainClassName = 'XStreamExample'

dependencies {
    groovy 'org.codehaus.groovy:groovy:2.0.5'
    compile 'com.thoughtworks.xstream:xstream:1.4.3'
}

repositories {
    mavenCentral()
}

扫码关注云+社区