`contentObject` 在 JAXBSource 构造函数中表示什么。

huangapple go评论74阅读模式
英文:

What is contentObject in the constructor of JAXBSource

问题

我必须创建一个程序,从(到)文件中读取(和写入)一个人的信息。写入部分已经正常工作。为了读取人的信息,我正在使用一个使用JAXBSource的教程。在JAXBSource的构造函数中:

JAXBSource(JAXBContext context, Object contentObject);

有一个叫做contentObject的对象,我不明白它应该是什么数据类型,以及它的用途是什么。或许有人可以帮助我。

英文:

I have to create a program which reads (and writes) a person from (to) a file. The writing part worked fine. To read the person I'm using a tutorial which uses JAXBSource. In the constructor of JAXBSource:

JAXBSource(JAXBContext context, Object contentObject);

there is this Object contentObject, which I don't understand what datatype it should be and what it's used for. Maybe someone can help me.

答案1

得分: 1

Short Answer

contentObject是您要提供给XML处理的任何对象。例如,这个过程可以是一个“转换”过程。

如果您有一个Person类,并且已经创建了一个person对象,那么您可以有:

JAXBSource source = new JAXBSource(context, person);

然而,我认为问题中可能存在一些误解。

您提到您可以成功地将一个person对象写入文件(我假设是XML)。但现在您想要从文件中读取数据,然后创建一个新的person对象。

但是,JAXBSource 从对象开始(如上所示),然后通常将该对象写入到某个新目标(例如文件)中。而且,正如我提到的,它允许在这一过程中对数据进行转换。

如果您只想将一个对象写入XML文件,然后将该XML数据读取回对象中,那么您可以简化代码,使用javax.xml.bind.Marshallerjavax.xml.bind.Unmarshaller

Longer Answer - With Examples

为了帮助澄清,以下是一些示例,从最简单的方法开始。

假设我们有以下Person类:

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Person {
    
    private String firstName;
    private String lastName;

    // getters and setters not shown here
}

示例 1 - 写入文件

这将对象写入文件中:

public void writeObjectToFile() throws JAXBException {
    JAXBContext jc = JAXBContext.newInstance(Person.class);
    Person person = new Person();
    person.setFirstName("Jack");
    person.setLastName("Frost");
    File xmlFile2 = new File("C:/tmp/files/person2.xml");

    Marshaller marshaller = jc.createMarshaller();
    marshaller.marshal(person, xmlFile2);
}

示例 2 - 从文件读取

这从示例1创建的文件中读取数据:

public void readObjectFromFile() throws JAXBException {
    JAXBContext jc = JAXBContext.newInstance(Person.class);
    Unmarshaller unmarshaller = jc.createUnmarshaller();
    File xmlFile = new File("C:/tmp/files/person2.xml");
    Person person = (Person) unmarshaller.unmarshal(xmlFile);
    System.out.println(person.getFirstName() + " " + person.getLastName());
}

在上述两个示例中,我们没有对数据执行任何自定义转换,也不需要使用JAXBSource(或JAXBResult - 见下文)。简单的编组和解组即可。

示例 3 - 从对象到文件的转换

public void transformObjectToFile() throws JAXBException,
        TransformerConfigurationException, TransformerException, IOException {
    JAXBContext jc = JAXBContext.newInstance(Person.class);
    Person person = new Person();
    person.setFirstName("John");
    person.setLastName("Smith");

    JAXBSource source = new JAXBSource(jc, person);
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer t = tf.newTransformer(new StreamSource("C:/tmp/files/person.xslt"));

    Writer writer = new FileWriter("C:/tmp/files/person.xml");
    t.transform(source, new StreamResult(writer));
}

在示例3中有更多的代码 - 还有一个新的XSLT文件,其中包含我们想要应用于从Person对象生成的XML的转换规则。这是您在问题中提到的使用JAXBSource构造函数的地方。

在我的测试中,我使用了一个实际上不会改变XML的XSLT文件 - 它只是将从Java对象到XML文件的数据传递给了它:

<?xml version="1.0"?>
<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:stylesheet>

但如果我想重新排列XML,这就是放置这些指令的地方。

示例 4 - 从文件到对象的转换

这最后一个示例是示例3的反向过程。它从示例3的文件中创建一个新的Person对象:

public void transformFileToObject() throws JAXBException,
        TransformerConfigurationException, TransformerException {
    JAXBContext jc = JAXBContext.newInstance(Person.class);

    JAXBResult result = new JAXBResult(jc);
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer t = tf.newTransformer(new StreamSource("C:/tmp/files/person.xslt"));

    t.transform(new StreamSource("C:/tmp/files/person.xml"), result);

    Person person = (Person) result.getResult();
    System.out.println(person.getFirstName() + " " + person.getLastName());
}

再次说明,我在示例中使用的转换是“根本没有转换”,这是我的示例。

最后,以下是上述所有相关的导入:

import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.util.JAXBSource;
import javax.xml.bind.util.JAXBResult;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.Writer;
import java.io.FileWriter;
import java.io.IOException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
英文:

Short Answer

The contentObject is whatever object you want to provide as input into your XML process. For example, this process could be a transformation process.

So, if you have a Person class, and you have created a person object, then you would have:

JAXBSource source = new JAXBSource(context, person);

However, I think there may be a couple misunderstandings in the question.

You mentioned you can successfully write a person object to a file (as XML, I assume). But now you want to read that data back from the file into a new person object.

But a JAXBSource starts with the object (as shown above) and then typically writes that object to some new target (e.g. a file). And, as I mentioned, it alows for a transformation of the data along the way.

If all you want to do is write an object to an XML file, and then read that XML data back into an object, then you can simplify the code by using javax.xml.bind.Marshaller and javax.xml.bind.Unarshaller.

Longer Answer - With Examples

To help clarify, here are some examples - starting with the simplest approach.

Assume we have the following Person class:

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Person {
    
    private String firstName;
    private String lastName;

    // getters and setters not shown here
}

Example 1 - Writing to a File

    public void writeObjectToFile() throws JAXBException {
        JAXBContext jc = JAXBContext.newInstance(Person.class);
        Person person = new Person();
        person.setFirstName(&quot;Jack&quot;);
        person.setLastName(&quot;Frost&quot;);
        File xmlFile2 = new File(&quot;C:/tmp/files/person2.xml&quot;);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.marshal(person, xmlFile2);
    }

This writes the following basic XML to the file:

&lt;person&gt;
  &lt;firstName&gt;Jack&lt;/firstName&gt;
  &lt;lastName&gt;Frost&lt;/lastName&gt;
&lt;/person&gt;

Example 2 - Reading From the File

This reads from the file we created in example 1:

    public void readObjectFromFile() throws JAXBException {
        JAXBContext jc = JAXBContext.newInstance(Person.class);
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        File xmlFile = new File(&quot;C:/tmp/files/person2.xml&quot;);
        Person person = (Person) unmarshaller.unmarshal(xmlFile);
        System.out.println(person.getFirstName() + &quot; &quot; + person.getLastName());
    }

In both of the above examples, we did not perform any custom transformation of the data - and we did not need to use JAXBSource (or JAXBResult - see below).

Simple marshalling and unmarshalling was sufficient.

Example 3 - Transforming from Object to File

    public void transformObjectToFile() throws JAXBException,
            TransformerConfigurationException, TransformerException, IOException {
        JAXBContext jc = JAXBContext.newInstance(Person.class);
        Person person = new Person();
        person.setFirstName(&quot;John&quot;);
        person.setLastName(&quot;Smith&quot;);

        JAXBSource source = new JAXBSource(jc, person);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer t = tf.newTransformer(new StreamSource(&quot;C:/tmp/files/person.xslt&quot;));

        Writer writer = new FileWriter(&quot;C:/tmp/files/person.xml&quot;);
        t.transform(source, new StreamResult(writer));
    }

In example 3 there is more code - and a new XSLT file, which contains the transformation rules we want to apply to the XML generated from the Person object. This is where we use the JAXBSource constructor from your question.

In my test, I used a XSLT file which does not actually change the XML - it just passes it through unchanged from the Java object to the XML file:

 xmlns:xsl=&quot;http://www.w3.org/1999/XSL/Transform&quot;&gt;
    &lt;xsl:template match=&quot;node()|@*&quot;&gt;
      &lt;xsl:copy&gt;
        &lt;xsl:apply-templates select=&quot;node()|@*&quot;/&gt;
      &lt;/xsl:copy&gt;
    &lt;/xsl:template&gt;
&lt;/xsl:stylesheet&gt;

But if I wanted to re-arrange the XML, this is where those instructions would be placed.

Example 4 - Transforming from File to Object

This final example is the reverse of example 3. It takes the example 3 file and creates a new Person object:

    public void transformFileToObject() throws JAXBException,
            TransformerConfigurationException, TransformerException {
        JAXBContext jc = JAXBContext.newInstance(Person.class);

        JAXBResult result = new JAXBResult(jc);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer t = tf.newTransformer(new StreamSource(&quot;C:/tmp/files/person.xslt&quot;));

        t.transform(new StreamSource(&quot;C:/tmp/files/person.xml&quot;), result);

        Person person = (Person) result.getResult();
        System.out.println(person.getFirstName() + &quot; &quot; + person.getLastName());
    }

Again, the transformation I use is "no transformation at all", in my example.

Finally, here are all the related imports for the above:

import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.util.JAXBSource;
import javax.xml.bind.util.JAXBResult;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.Writer;
import java.io.FileWriter;
import java.io.IOException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

huangapple
  • 本文由 发表于 2020年9月8日 16:46:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/63790341.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定