[英]Search a DOM created from xml document and copy values to a spreadsheet/csv
我已經將XML文檔讀入JAVA DOM數據結構。 我可以搜索文檔並使用For循環查找信息。 然后我可以向終端打印父節點和子節點中保存的所有信息。
但是,我需要做的是獲取某些元素並將它們打印到電子表格中。 所以以某種方式將值寫入csv文檔,然后我可以將其導入Excel。
這將節省我很多時間,因為我必須手動將值復制到電子表格中,這將需要數周時間。 所以自動化它是最好的選擇,但我缺乏Java經驗。 任何幫助表示贊賞。
使用單個DOM解析器實例執行此操作可能非常麻煩。 為此,我建議創建一個包含xml文件中所有數據的JavaBean。 一個名為toCsv
的簡單方法將遍歷所有項目並返回格式化內容或將其打印到csv文件。 如果您遵循這種方法,您可以簡單地使用Java Architecture for XML Binding (JAXB)
,它將為您執行XML和Java對象之間的編組和解組。 不再需要可能難以維護的自定義DOM解析器實現。 JAXB使用注釋來定義解析器規則。 這是一個簡單的例子:
public interface DataEntity {
/**
* NameSpace of XSD schema files.
*/
public final static String NSP = "https://localhost/project/xsd/";
}
import java.io.Serializable;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import at.fhj.ase.dao.data.validation.ValidationHelper;
/**
* Represents a product category
*
*/
@XmlRootElement(name = "category", namespace = DataEntity.NSP)
public class Category implements Serializable {
/**
*
*/
private static final long serialVersionUID = -487248720383832971L;
private Integer id;
private String name;
private String description;
protected Category() {
}
public Category(final Integer id, final String name,
final String description) {
setId(id);
setName(name);
setDescription(description);
}
@XmlAttribute
public Integer getId() {
return id;
}
private void setId(Integer id) {
ValidationHelper.validateId(id);
this.id = id;
}
@XmlElement(namespace = DataEntity.NSP)
public String getName() {
return name;
}
private void setName(String name) {
ValidationHelper.validateSingleName(name, "name");
this.name = name;
}
@XmlElement(namespace = DataEntity.NSP)
public String getDescription() {
return description;
}
private void setDescription(String description) {
ValidationHelper.validateSingleName(description, "description");
this.description = description;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Id: ").append(id).append(" Name: ").append(getName())
.append(" Description: ").append(description);
return sb.toString();
}
}
並將xml文件作為輸入:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<category xmlns="https://localhost/project/xsd/" id="1">
<description>des_swdevelopment</description>
<name>swdevelopment</name>
</category>
以及如何從xml 解組到java: Interface Unmarshaller
你只需要添加toCsv
方法就完成了。 這種方法可以節省大量時間並且易於維護。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.