【问题标题】:Retrieve XMl Data Using Java使用 Java 检索 XML 数据
【发布时间】:2012-07-04 13:12:00
【问题描述】:

我对 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

【问题讨论】:

    标签: java xml xml-parsing


    【解决方案1】:

    我假设您已经创建了一个包含四列的数据库表 - 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
    

    【讨论】:

    • +1 @sreehari:确实 getTextValue 辅助方法至关重要!但我不应该说它真的很简单,因为实现这个非常普遍的需求需要复杂性 XD
    • 嗨,这不是我想要的,我需要动态创建列名,而不是一个又一个我想要的列和行格式
    【解决方案2】:

    我不确定这个 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}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-01
      • 2013-10-06
      • 2016-01-30
      相关资源
      最近更新 更多