使用对先前标记的引用解析XML,并使用与某些类的子类型对应的子代

时间:2012-12-27 11:03:53

标签: java xml-parsing xstream xml-deserialization

我必须处理以下场景(的变体)。我的模型类是:

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>

等。 (我不想要<engine> - 代码,我想要<v6engine> - 代码 <v12engine> - 代码。

此外,我需要能够根据标识符返回“预定义”品牌,如上面的品牌ID所示。 (例如,在反序列化期间保持Map<Integer, String> predefinedBrands)。我不知道XStream是否适合这种情况。

我意识到这可以通过推或拉解析器(例如SAX或StAX)或DOM库“手动”完成。但是我希望有更多的自动化。理想情况下,我应该能够添加类(例如新的Engine)并立即开始在XML中使用它们。 (XStream绝不是一个要求,最优雅的解决方案赢得了赏金。)

3 个答案:

答案 0 :(得分:11)

JAXB(javax.xml.bind)可以完成你所追求的一切,虽然有些比其他更容易。为了简单起见,我将假设您的所有XML文件都有一个命名空间 - 如果它们没有,那就更难了,但是可以使用StAX API进行处理。

<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子类。所以给出

的XML
<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具有基于@XmlID@XmlIDREF的交叉引用机制,但这些机制要求ID属性是有效的XML ID,即XML名称,特别是不完全由数字组成。但是,只要您不需要“前向”引用(即<car>引用尚未“声明的<brand>,那么自己跟踪交叉引用并不困难。 “)。

第一步是定义一个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的{​​{1}}字段:

Car

最后一部分是确保在顶层找到的@XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class Car { @XmlJavaTypeAdapter(BrandAdapter.class) String brand; @XmlElementRef Engine engine; } 元素保存在缓存中。这是一个完整的例子

<brand>

答案 1 :(得分:4)

这是XStream的解决方案,因为您似乎已经熟悉它,因为它是一个非常灵活的XML工具。它是在Groovy中完成的,因为它比Java好得多。移植到Java将是相当微不足道的。请注意,我选择对结果进行一些后处理,而不是试图让XStream为我完成所有工作。具体而言,事后处理“品牌参考”。我可以在编组中做到这一点,但我认为这种方法更清晰,让你的选择更加开放,以便将来修改。此外,这种方法允许“品牌”元素出现在整个文档的任何地方,包括在引用它们的汽车之后 - 如果您在飞行中进行替换,我认为您无法实现。

带注释的解决方案

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'}}

没有注释的解决方案

P.S。只是为了笑容,这是没有注释的同样的事情。它完全相同,除了注释类之外,new XStream()下还有一些额外的行可以完成注释之前的所有操作。输出相同。

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" }

P.P.S。如果您安装了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()
}

答案 2 :(得分:1)

您可以尝试引用here来获取一些想法。

就个人而言,我会使用DOM Parser来获取XML文件的内容。

示例:

import java.io.*;
import javax.xml.parsers.*;

import org.w3c.dom.*;

public class DOMExample {

  public static void main(String[] args) throws Exception {

    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();

    File file = new File("filename.xml");
    Document doc = builder.parse(file);

    NodeList carList = doc.getElementsByTagName("car");
    for (int i = 0; i < carList.getLength(); ++i) {

        Element carElem = (Element)carList.item(i);

        Element brandElem = (Element)carElem.getElementsByTagName("brand").item(0);
        Element engineElem = (Element)carElem.getElementsByTagName("v12engine").item(0);

        String brand= brandElem.getTextContent();
        String engine= engineElem.getTextContent();

        System.out.println(brand+ ", " + engine);

        // TODO Do something with the desired information.
    }       
  }
}

如果您知道标签名称的可能内容,这将非常有效。有许多方法可以解析XML文件。希望你能想出一些适合你的东西。祝你好运!