如何让jaxb在解组时忽略某些数据 [英] How to get jaxb to Ignore certain data during unmarshalling
问题描述
我有一个xml结构Filter,可以在名为Filter的java类中进行解组。
I have a xml structure "Filter" that get unmarshalled into in a java class called "Filter".
XML状态看起来大致如下:
The XML state looks roughly like:
<filter>
<propertyType>
<propertyName>prop1</propertyName>
<propertyValue>val1</propertyValue>
</propertyType>
<propertyType>
<propertyName>prop2</propertyName>
<propertyValue>val2</propertyValue>
</propertyType>
</filter>
通常情况下,效果很好。
Ordinarily, it works great.
但是,在某些情况下,其中一个属性值本身包含xml结构(请参阅下面的第二个propertyValue):
However, there are certain situations where one of these property values itself contains xml structure (see second propertyValue below):
<filter>
<propertyType>
<propertyName>prop1</propertyName>
<propertyValue>val1</propertyValue>
</propertyType>
<propertyType>
<propertyName>prop2</propertyName>
<propertyValue><nodeA><nodeB>valB</nodeB></nodeA></propertyValue>
</propertyType>
</filter>
这里的问题是在解组此结构后,propertyValue为null。
The problem here is that after unmarshalling this structure, the propertyValue is null.
我希望能够让unmarshalling忽略这个看起来像xml的代码并将其视为一个简单的字符串值。
I would like to simply be able to have the unmarshalling ignore this xml-looking code and treat it as a simple string value.
有谁知道我怎么做到这一点?感谢您的回复!
Does anyone know how I can accomplish this? Thanks for any reply!
推荐答案
对于这个用例,我将创建一个将转换XML文档的XSLT。然后使用javax.xml.transform。* API,将XML转换为JAXBResult以解组对象:
For this use case I would create an XSLT that will convert the XML document. Then using the javax.xml.transform.* APIs, transform the XML to a JAXBResult to unmarshal the object:
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.util.JAXBResult;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamSource;
public class Demo {
public static void main(String[] args) throws Exception {
TransformerFactory tf = TransformerFactory.newInstance();
File xsltFile = new File("transform.xsl");
StreamSource xsltSource = new StreamSource(xsltFile);
Transformer transformer = tf.newTransformer(xsltSource);
File xml = new File("input.xml");
StreamSource xmlSource = new StreamSource(xml);
JAXBContext jc = JAXBContext.newInstance(Filter.class);
JAXBResult jaxbResult = new JAXBResult(jc);
transformer.transform(xmlSource, jaxbResult);
Filter filter = (Filter) jaxbResult.getResult();
}
}
transform.xsl
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="node() | @*">
<xsl:copy>
<xsl:apply-templates select="node() | @*" />
</xsl:copy>
</xsl:template>
<xsl:template match="propertyValue"> <xsl:value-of select="descendents"/>
<xsl:element name="propertyValue">
<xsl:value-of select="node()"/>
</xsl:element>
</xsl:template>
</xsl:stylesheet>
这篇关于如何让jaxb在解组时忽略某些数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!