我正在制作一个视频转换器作为假期项目。我计划使用 XML 文件来表示待处理的任务,以便用户可以保存任务。它看起来像这样:
<?xml version="1.0" ?>
<task-list>
<task>
<input-location> </input-location>
<output-location> </output-location>
<bit-rate> </bit-rate>
<output-width> </output-width>
<output-height> </output-height>
<target-device> </target-device>
</task>
.
.
.
.
</task-list>
现在,这就是我的想法:
1. 将其解析为 org.w3c.dom.Document
2.使用XPath获取NodeList
其中将包含所有 <task>
还有 children 。
3.创建Vector<Task>
哪里Task
是一个自定义类。每个Task
对象将包含 org.w3c.dom.Node
4. 在 Node
的上下文中使用 XPath与每个Task
相关联反对获取相关信息。
但是这里有一个问题:如何改变 Node
?也许用户想要更改输出位置。我将不得不对相关的Task
进行更改对象的Node
,org.w3c.dom.Document
(它还保存已保存文件中的节点副本)并将其保存到文件中(为了下次运行转换器时保持一致)。
使用 XPath 会变得非常麻烦。我认为 XPath 对于数据“恢复”很有用,但不适合更改。
公共(public)类任务
public class Task{
Node taskInfo;
JProgressBar progressBar; // Visual feedback to the user
.
.
.
.
.
// getters and setters
}
我可以使用 XPath 使 getters 工作。 Setter 是问题所在。
最佳答案
您可以使用任何 JAXB (JSR-222) 执行以下操作执行。从 Java SE 6 开始,JDK/JRE 中包含一个实现:
JAVA模型
任务列表
import java.util.List;
import javax.xml.bind.annotation.*;
@XmlRootElement(name="task-list")
@XmlAccessorType(XmlAccessType.FIELD)
public class TaskList {
@XmlElement(name="task")
private List<Task> tasks;
}
任务
import javax.xml.bind.annotation.*;
@XmlAccessorType(XmlAccessType.FIELD)
public class Task {
@XmlElement(name="input-location")
private String inputLocation;
@XmlElement(name="output-location")
private String outputLocation;
@XmlElement(name="bit-rate")
private int bitRate;
@XmlElement(name="output-width")
private int outputWidth;
@XmlElement(name="output-height")
private int outputHeight;
@XmlElement(name="target-device")
private String targetDevice;
}
演示代码
演示
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(TaskList.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum16579050/input.xml");
TaskList taskList = (TaskList) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(taskList, System.out);
}
}
输入.xml/输出
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<task-list>
<task>
<input-location>foo input</input-location>
<output-location>foo output</output-location>
<bit-rate>1</bit-rate>
<output-width>2</output-width>
<output-height>3</output-height>
<target-device>foo</target-device>
</task>
<task>
<input-location>bar input</input-location>
<output-location>bar output</output-location>
<bit-rate>4</bit-rate>
<output-width>5</output-width>
<output-height>6</output-height>
<target-device>bar</target-device>
</task>
</task-list>
关于java - 如何有效管理各种转换任务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16579050/