给出以下XML结构:
<clinical_study>
<primary_outcome>
<measure></measure>
<time_frame></time_frame>
<safety_issue></safety_issue>
<description></description>
</primary_outcome>
<secondary_outcome>
<measure></measure>
<time_frame></time_frame>
<safety_issue></safety_issue>
<description></description>
</secondary_outcome>
</clinical_study>
我想解析这些属性标记中的值,并将它们转储到名为“CLINICAL_STUDY”的Oracle表中,并使用以下列结构:
desc clinical_study
Name Null Type
---------------------------- -------- -----------------
PRIMARY_OUTCOME_MEASURE VARCHAR2(50)
PRIMARY_OUTCOME_TIME_FRAME VARCHAR2(50)
PRIMARY_OUTCOME_SAFETY_ISSUE VARCHAR2(50)
PRIMARY_OUTCOME_DESCRIPTION VARCHAR2(4000)
SECONDARY_OUTCOME_MEASURE VARCHAR2(50)
SECONDARY_OUTCOME_TIME_FRAME VARCHAR2(50)
SECONDARY_OUTCOME_SAFETY_ISSUE VARCHAR2(50)
SECONDARY_OUTCOME_DESCRIPTION VARCHAR2(4000)
我意识到有几种方法可以实现这一点,但我不太确定哪种方法最简单。我倾向于XSLT,它会“压平”数据,然后很容易转换成表结构,但好奇的是,如果有一个更简单的方法。提前谢谢。
答案 0 :(得分:1)
如果使用Java进行编程,则不需要运行XSLT转换。您应该能够从XML文件中读取数据并将其写入数据库。
当然有多种方法可以做到,但一种方法是使用JAXB读入数据。 (如果你有足够小的数据可以在处理时将它保存在内存中,这基本上可以工作。如果你有大量的数据,你可能想要使用像StAX这样的流式XML解析器API。)
首先,您可以创建一对类来表示您的输入数据,并使用JAXB注释进行注释,这些注释定义了XML的映射。
@XmlAccessorType(XmlAccessType.FIELD)
public class Outcome {
@XmlElement(name="measure")
private String measure;
@XmlElement(name="time_frame")
private String timeFrame;
@XmlElement(name="safety_issue")
private String safetyIssue;
@XmlElement(name="description")
private String description;
// getters and setters omitted for brevity
}
和
inputStream
然后你可以从XML中读取或解析你的数据(假设 JAXBContext context = JAXBContext.newInstance(ClinicalStudy.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
ClinicalStudy clinicalStudy = (ClinicalStudy) unmarshaller.unmarshal(inputStream);
是XML内容的流)。
conn
并插入数据库(假设 PreparedStatement pstmt = conn.prepareStatement(
"INSERT INTO clinical_study ("
+ "PRIMARY_OUTCOME_MEASURE, "
+ "PRIMARY_OUTCOME_TIME_FRAME, "
+ "PRIMARY_OUTCOME_SAFETY_ISSUE, "
+ "PRIMARY_OUTCOME_DESCRIPTION, "
+ "SECONDARY_OUTCOME_MEASURE, "
+ "SECONDARY_OUTCOME_TIME_FRAME, "
+ "SECONDARY_OUTCOME_SAFETY_ISSUE, "
+ "SECONDARY_OUTCOME_DESCRIPTION) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
pstmt.setString(1, clinicalStudy.getPrimaryOutcome().getMeasure());
pstmt.setString(2, clinicalStudy.getPrimaryOutcome().getTimeFrame());
pstmt.setString(3, clinicalStudy.getPrimaryOutcome().getSafetyIssue());
pstmt.setString(4, clinicalStudy.getPrimaryOutcome().getDescription());
pstmt.setString(5, clinicalStudy.getSecondaryOutcome().getMeasure());
pstmt.setString(6, clinicalStudy.getSecondaryOutcome().getTimeFrame());
pstmt.setString(7, clinicalStudy.getSecondaryOutcome().getSafetyIssue());
pstmt.setString(8, clinicalStudy.getSecondaryOutcome().getDescription());
pstmt.execute();
是JDBC数据库连接)。
def exprNeg[T:Numeric](value: T): T = {
val n = implicitly[Numeric[T]]
n.negate(value)
}