我是Java和Xml解析的新手。我的要求是获取一个xml文件,并使用java以表格和列格式将XML文件的数据存储在数据库中。我尝试在谷歌获得正确的解决方案。但我很无奈。到目前为止我所做的是,我可以动态获取xml数据并存储标签名称或值。但我的意思是只使用一次标记名称作为列名和与行格式的特定列相关的数据,任何人都可以请更正我的代码。
<?xml version="1.0"?>
<company>
<staff>
<firstname>yong</firstname>
<lastname>mook kim</lastname>
<nickname>mkyong</nickname>
<salary>100000</salary>
</staff>
<staff>
<firstname>low</firstname>
<lastname>yin fong</lastname>
<nickname>fong fong</nickname>
<salary>200000</salary>
</staff>
</company>
Java代码
import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.*;
public class XmlData{
static public void main(String[] arg){
try {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter XML File Path: ");
String xmlFile = bf.readLine();
//Store the String into the File
File file = new File(xmlFile);
if(file.exists()){
// Create a factory
DocumentBuilderFactory factory =DocumentBuilderFactory.newInstance();
// Use the factory to create a builder
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(xmlFile);
Element docEle = doc.getDocumentElement();
System.out.println("Root element of the document: "+ docEle.getNodeName());
// Get a list of all elements in the document
NodeList list = doc.getElementsByTagName("*");
int totalElements = list.getLength();
System.out.println("XML Elements: " + totalElements);
for (int i=0; i<list.getLength(); i++)
{
// Get element
Element element = (Element)list.item(i);
String tag=element.getTagName();
String name=list.item(0).getChildNodes().item(0).getNodeValue();
System.out.println(name);
System.out.print(tag);
System.out.print(" ");
//System.out.println(element.getNodeName());
}
}
else{
System.out.print("File not found!");
}
}
catch (Exception e) {
System.exit(1);
}
}
}
此代码的输出:
company
staff
firstname
lastname
nickname
salary
staff
firstname
lastname
nickname
salary
预期产出:
FirstName, Lastname, nickname , salary //column
yong ,mook kim, mkyong , 100000 // rows
low ,yin fong, fong fong ,200000
我假设您已经创建了一个包含四列的数据库表 - FirstNAme,LastName,NickName,Salary。
在数据库中读取数据和存储非常简单。
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
public class ParseStaff {
public static void main(String [] args){
parseFile();
}
public static void parseFile() {
//get the factory
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
//Using factory get an instance of document builder
DocumentBuilder db = dbf.newDocumentBuilder();
//parse using builder to get DOM representation of the XML file
//Document dom = db.parse("employees.xml");
Document dom = db.parse("C:\\GAE\\NetBeansProjects\\Test\\src\\statff.xml");
//get the root element
Element docEle = dom.getDocumentElement();
//get a nodelist of elements
NodeList nl = docEle.getElementsByTagName("staff");
if (nl != null && nl.getLength() > 0) {
for (int i = 0; i < nl.getLength(); i++) {
//get the employee element
Element el = (Element) nl.item(i);
String firstname = getTextValue(el, "firstname");
String lastname = getTextValue(el, "lastname");
String nickname = getTextValue(el, "nickname");
int salary = getIntValue(el, "salary");
System.out.println(firstname);
System.out.println(lastname);
System.out.println(nickname);
System.out.println(salary);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static String getTextValue(Element ele, String tagName) {
String textVal = null;
NodeList nl = ele.getElementsByTagName(tagName);
if (nl != null && nl.getLength() > 0) {
Element el = (Element) nl.item(0);
textVal = el.getFirstChild().getNodeValue();
}
return textVal;
}
private static int getIntValue(Element ele, String tagName) {
return Integer.parseInt(getTextValue(ele, tagName));
}
}
将打印:
yong
mook kim
mkyong
100000
low
yin fong
fong fong
200000
我不确定这个XML是如何巨大的。但是如果xml很大,则无法将所有XML导入内存。
因此,您可以使用Declarative Stream Mapping (DSM)库。
DSM允许您将XML作为流处理并部分处理数据。
首先,您必须按如下方式定义yaml映射文件。
result:
type: object # result is map
path: /.+staff # path is regex. its match with /company/staff
function: processStuff # call processStuff function when /company/stuff tag is closed
fields:
firstName: # firstName is not same as firstname (camel case)
path: firstname
lastName:
path: lastname
nickName:
path: nickname
salary: long
为流程人员创建FunctionExecutor。
FunctionExecutor processStuff=new FunctionExecutor(){
@Override
public void execute(Params params) {
// directly serialize Stuff class
//Stuff stuff=params.getCurrentNode().toObject(Stuff.class);
Map<String,Object> stuff= (Map<String,Object>)params.getCurrentNode().toObject();
System.out.println(stuff);
// process stuff ; save to db. call service etc.
}
};
使用DSM处理xml
DSMBuilder builder = new DSMBuilder(new File("path/to/mapping.yaml")).setType(DSMBuilder.TYPE.XML);
// register processStuff Function
builder.registerFunction("processStuff",processStuff);
DSM dsm= builder.create();
Object object = dsm.toObject(xmlContent);
输出:
{firstName=yong, lastName=mook kim, nickName=mkyong, salary=100000}
{firstName=low, lastName=yin fong, nickName=fong fong, salary=200000}