论坛首页 入门技术论坛

JDOM读写XML文件

浏览 10155 次
该帖已经被评为新手帖
作者 正文
   发表时间:2008-03-12  

package com.test;
import org.jdom.*;
import org.jdom.input.*;
import org.jdom.output.*;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.List;

public class MyJDom {

    public static void main(String[] args) throws Exception{
        SAXBuilder sb=new SAXBuilder();//建立构造器
        Document doc=sb.build(new FileInputStream("src/xml/abc.xml"));//读入指定文件

        Element root=doc.getRootElement();//获得根节点
        List list=root.getChildren();//将根节点下的所有子节点放入List中

        for(int i=0;i<list.size();i++) {

            System.out.println("---------------------------");

            Element item=(Element)list.get(i);//取得节点实例

            String id=item.getAttribute("id").getValue();//取得属性值

            System.out.println("id-->"+id);


            Element sub=item.getChild("title");//取得当前节点的字节点
            String text=sub.getText();//取得当前节点的值

             System.out.println("Title-->"+text);

            if(item.getChild("content").getChildren().size()>0){
            Element sub2=item.getChild("content").getChild("name");
                String text2=sub2.getText();

                System.out.println("name-->"+text2);
            }
           


            Element sub3=item.getChild("email");
            String text3=sub3.getText();

            System.out.println("Email-->"+text3);
        }
      }
}

附:要读取的xml文件如下:abc.xml

<?xml version="1.0" encoding="gb2312"?>
<messages>
<message id="1">
   <title>11</title>
   <content>
    <name>lvpingyu</name>
    <age>23</age>
   </content>
   <email>33</email>
</message>
<message id="2">
   <title>44</title>
   <content>
    <name>lvpingyu</name>
    <age>23</age>
   </content>
   <email>66</email>
</message>
</messages>

------------------------------------------------------------------------------------------------------

应用jdom生成xml文件

import java.io.FileOutputStream;
import java.io.IOException;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.output.XMLOutputter;
public class JavaXML {
public void BuildXMLDoc() throws IOException, JDOMException {
   // 创建根节点 list;   
   Element root = new Element("list");
   // 根节点添加到文档中;   
   Document Doc = new Document(root);
   // 此处 for 循环可替换成 遍历 数据库表的结果集操作;   
   for (int i = 0; i < 5; i++) {
    // 创建节点 user;
    Element elements = new Element("company");
    // 给 company 节点添加属性 id;
    elements.setAttribute("id", "" + i);
    // 给 company 节点添加子节点并赋值
    // new Element("company_name")中的 "company_name" 替换成表中相应字段,setText("name")中 "name 替换成表中记录值;
    elements.addContent(new Element("company_name").setText("name" + i));
    elements.addContent(new Element("company_email").setText("@" + i+ ".com"));
    // 给父节点list添加company子节点;  
    root.addContent(elements);
   }
   XMLOutputter XMLOut = new XMLOutputter();
   // 输出company_list.xml文件;  
   XMLOut.output(Doc, new FileOutputStream("company_list.xml"));
}
/**
   * 主方法用于测试
   * @param args
   */
public static void main(String[] args) {
   try {
    JavaXML javaXML = new JavaXML();
    javaXML.BuildXMLDoc();
   } catch (Exception e) {
    e.printStackTrace();
   }
}
}
  
   发表时间:2008-03-31  
yangjinhappy 写道

package com.test;
import org.jdom.*;
import org.jdom.input.*;
import org.jdom.output.*;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.List;

public class MyJDom {

    public static void main(String[] args) throws Exception{
        SAXBuilder sb=new SAXBuilder();//建立构造器
        Document doc=sb.build(new FileInputStream("src/xml/abc.xml"));//读入指定文件

        Element root=doc.getRootElement();//获得根节点
        List list=root.getChildren();//将根节点下的所有子节点放入List中

        for(int i=0;i<list.size();i++) {

            System.out.println("---------------------------");

            Element item=(Element)list.get(i);//取得节点实例

            String id=item.getAttribute("id").getValue();//取得属性值

            System.out.println("id-->"+id);


            Element sub=item.getChild("title");//取得当前节点的字节点
            String text=sub.getText();//取得当前节点的值

             System.out.println("Title-->"+text);

            if(item.getChild("content").getChildren().size()>0){
            Element sub2=item.getChild("content").getChild("name");
                String text2=sub2.getText();

                System.out.println("name-->"+text2);
            }
           


            Element sub3=item.getChild("email");
            String text3=sub3.getText();

            System.out.println("Email-->"+text3);
        }
      }
}

附:要读取的xml文件如下:abc.xml

<?xml version="1.0" encoding="gb2312"?>
<messages>
<message id="1">
   <title>11</title>
   <content>
    <name>lvpingyu</name>
    <age>23</age>
   </content>
   <email>33</email>
</message>
<message id="2">
   <title>44</title>
   <content>
    <name>lvpingyu</name>
    <age>23</age>
   </content>
   <email>66</email>
</message>
</messages>

------------------------------------------------------------------------------------------------------

应用jdom生成xml文件

import java.io.FileOutputStream;
import java.io.IOException;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.output.XMLOutputter;
public class JavaXML {
public void BuildXMLDoc() throws IOException, JDOMException {
   // 创建根节点 list;   
   Element root = new Element("list");
   // 根节点添加到文档中;   
   Document Doc = new Document(root);
   // 此处 for 循环可替换成 遍历 数据库表的结果集操作;   
   for (int i = 0; i < 5; i++) {
    // 创建节点 user;
    Element elements = new Element("company");
    // 给 company 节点添加属性 id;
    elements.setAttribute("id", "" + i);
    // 给 company 节点添加子节点并赋值
    // new Element("company_name")中的 "company_name" 替换成表中相应字段,setText("name")中 "name 替换成表中记录值;
    elements.addContent(new Element("company_name").setText("name" + i));
    elements.addContent(new Element("company_email").setText("@" + i+ ".com"));
    // 给父节点list添加company子节点;  
    root.addContent(elements);
   }
   XMLOutputter XMLOut = new XMLOutputter();
   // 输出company_list.xml文件;  
   XMLOut.output(Doc, new FileOutputStream("company_list.xml"));
}
/**
   * 主方法用于测试
   * @param args
   */
public static void main(String[] args) {
   try {
    JavaXML javaXML = new JavaXML();
    javaXML.BuildXMLDoc();
   } catch (Exception e) {
    e.printStackTrace();
   }
}
}
  
0 请登录后投票
   发表时间:2008-04-02  

请问一下,下面的这样的怎么解析啊?这是 我从webservice服务上返回的xml
<DataSet>
<xs:schema id="Airlines">
<xs:element name="Airlines" msdata:IsDataSet="true" msdata:UseCurrentLocale="true">
<xs:complexType>
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="AirlinesTime">
<xs:complexType>
<xs:sequence>
<xs:element name="Company" type="xs:string" minOccurs="0"/>
<xs:element name="AirlineCode" type="xs:string" minOccurs="0"/>
<xs:element name="StartDrome" type="xs:string" minOccurs="0"/>
<xs:element name="ArriveDrome" type="xs:string" minOccurs="0"/>
<xs:element name="StartTime" type="xs:string" minOccurs="0"/>
<xs:element name="ArriveTime" type="xs:string" minOccurs="0"/>
<xs:element name="Mode" type="xs:string" minOccurs="0"/>
<xs:element name="AirlineStop" type="xs:string" minOccurs="0"/>
<xs:element name="Week" type="xs:string" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:choice>
</xs:complexType>
</xs:element>
</xs:schema>

<diffgr:diffgram>

<Airlines>

<AirlinesTime diffgr:id="AirlinesTime1" msdata:rowOrder="0" diffgr:hasChanges="inserted">
<Company><div class="pubFlights_fm">上海航空公司</div></Company>
<AirlineCode>FM9361</AirlineCode>
<StartDrome>浦东国际机场</StartDrome>
<ArriveDrome>天河机场</ArriveDrome>
<StartTime>08:40</StartTime>
<ArriveTime>10:15</ArriveTime>
<Mode>JET</Mode>
<AirlineStop>0</AirlineStop>
<Week>123456日</Week>
</AirlinesTime>

<AirlinesTime diffgr:id="AirlinesTime2" msdata:rowOrder="1" diffgr:hasChanges="inserted">
<Company><div class="pubFlights_cz">中国南方航空(集团)公司</div></Company>
<AirlineCode>CZ3572</AirlineCode>
<StartDrome>浦东国际机场</StartDrome>
<ArriveDrome>天河机场</ArriveDrome>
<StartTime>10:45</StartTime>
<ArriveTime>12:10</ArriveTime>
<Mode>737</Mode>
<AirlineStop>0</AirlineStop>
<Week>123456日</Week>
</AirlinesTime>

<AirlinesTime diffgr:id="AirlinesTime3" msdata:rowOrder="2" diffgr:hasChanges="inserted">
<Company><div class="pubFlights_mu">中国东方航空公司</div></Company>
<AirlineCode>MU2502</AirlineCode>
<StartDrome>浦东国际机场</StartDrome>
<ArriveDrome>天河机场</ArriveDrome>
<StartTime>10:45</StartTime>
<ArriveTime>12:45</ArriveTime>
<Mode>733</Mode>
<AirlineStop>0</AirlineStop>
<Week>123456日</Week>
</AirlinesTime>

<AirlinesTime diffgr:id="AirlinesTime4" msdata:rowOrder="3" diffgr:hasChanges="inserted">
<Company><div class="pubFlights_mu">中国东方航空公司</div></Company>
<AirlineCode>MU2504</AirlineCode>
<StartDrome>浦东国际机场</StartDrome>
<ArriveDrome>天河机场</ArriveDrome>
<StartTime>13:05</StartTime>
<ArriveTime>14:45</ArriveTime>
<Mode>JET</Mode>
<AirlineStop>0</AirlineStop>
<Week>123456日</Week>
</AirlinesTime>

<AirlinesTime diffgr:id="AirlinesTime5" msdata:rowOrder="4" diffgr:hasChanges="inserted">
<Company><div class="pubFlights_cz">中国南方航空(集团)公司</div></Company>
<AirlineCode>CZ3824</AirlineCode>
<StartDrome>浦东国际机场</StartDrome>
<ArriveDrome>天河机场</ArriveDrome>
<StartTime>13:45</StartTime>
<ArriveTime>15:15</ArriveTime>
<Mode>738</Mode>
<AirlineStop>0</AirlineStop>
<Week>123456日</Week>
</AirlinesTime>

<AirlinesTime diffgr:id="AirlinesTime6" msdata:rowOrder="5" diffgr:hasChanges="inserted">
<Company><div class="pubFlights_mu">中国东方航空公司</div></Company>
<AirlineCode>MU2506</AirlineCode>
<StartDrome>浦东国际机场</StartDrome>
<ArriveDrome>天河机场</ArriveDrome>
<StartTime>16:10</StartTime>
<ArriveTime>17:45</ArriveTime>
<Mode>733</Mode>
<AirlineStop>0</AirlineStop>
<Week>123456日</Week>
</AirlinesTime>

<AirlinesTime diffgr:id="AirlinesTime7" msdata:rowOrder="6" diffgr:hasChanges="inserted">
<Company><div class="pubFlights_cz">中国南方航空(集团)公司</div></Company>
<AirlineCode>CZ3580</AirlineCode>
<StartDrome>浦东国际机场</StartDrome>
<ArriveDrome>天河机场</ArriveDrome>
<StartTime>16:35</StartTime>
<ArriveTime>17:55</ArriveTime>
<Mode>738</Mode>
<AirlineStop>0</AirlineStop>
<Week>123456日</Week>
</AirlinesTime>

<AirlinesTime diffgr:id="AirlinesTime8" msdata:rowOrder="7" diffgr:hasChanges="inserted">
<Company><div class="pubFlights_mu">中国东方航空公司</div></Company>
<AirlineCode>MU2508</AirlineCode>
<StartDrome>浦东国际机场</StartDrome>
<ArriveDrome>天河机场</ArriveDrome>
<StartTime>18:05</StartTime>
<ArriveTime>19:45</ArriveTime>
<Mode>733</Mode>
<AirlineStop>0</AirlineStop>
<Week>124</Week>
</AirlinesTime>

<AirlinesTime diffgr:id="AirlinesTime9" msdata:rowOrder="8" diffgr:hasChanges="inserted">
<Company><div class="pubFlights_mu">中国东方航空公司</div></Company>
<AirlineCode>MU2508</AirlineCode>
<StartDrome>浦东国际机场</StartDrome>
<ArriveDrome>天河机场</ArriveDrome>
<StartTime>18:05</StartTime>
<ArriveTime>19:45</ArriveTime>
<Mode>JET</Mode>
<AirlineStop>0</AirlineStop>
<Week>356日</Week>
</AirlinesTime>

<AirlinesTime diffgr:id="AirlinesTime10" msdata:rowOrder="9" diffgr:hasChanges="inserted">
<Company><div class="pubFlights_fm">上海航空公司</div></Company>
<AirlineCode>FM9449</AirlineCode>
<StartDrome>浦东国际机场</StartDrome>
<ArriveDrome>天河机场</ArriveDrome>
<StartTime>19:10</StartTime>
<ArriveTime>20:35</ArriveTime>
<Mode>738</Mode>
<AirlineStop>0</AirlineStop>
<Week>123456日</Week>
</AirlinesTime>

<AirlinesTime diffgr:id="AirlinesTime11" msdata:rowOrder="10" diffgr:hasChanges="inserted">
<Company><div class="pubFlights_mu">中国东方航空公司</div></Company>
<AirlineCode>MU2510</AirlineCode>
<StartDrome>浦东国际机场</StartDrome>
<ArriveDrome>天河机场</ArriveDrome>
<StartTime>20:15</StartTime>
<ArriveTime>21:45</ArriveTime>
<Mode>738</Mode>
<AirlineStop>0</AirlineStop>
<Week>12</Week>
</AirlinesTime>

<AirlinesTime diffgr:id="AirlinesTime12" msdata:rowOrder="11" diffgr:hasChanges="inserted">
<Company><div class="pubFlights_cz">中国南方航空(集团)公司</div></Company>
<AirlineCode>CZ370</AirlineCode>
<StartDrome>浦东国际机场</StartDrome>
<ArriveDrome>天河机场</ArriveDrome>
<StartTime>20:55</StartTime>
<ArriveTime>22:25</ArriveTime>
<Mode>738</Mode>
<AirlineStop>0</AirlineStop>
<Week>123456日</Week>
</AirlinesTime>

<AirlinesTime diffgr:id="AirlinesTime13" msdata:rowOrder="12" diffgr:hasChanges="inserted">
<Company><div class="pubFlights_mu">中国东方航空公司</div></Company>
<AirlineCode>MU2512</AirlineCode>
<StartDrome>浦东国际机场</StartDrome>
<ArriveDrome>天河机场</ArriveDrome>
<StartTime>21:05</StartTime>
<ArriveTime>22:45</ArriveTime>
<Mode>733</Mode>
<AirlineStop>0</AirlineStop>
<Week>123456日</Week>
</AirlinesTime>

<AirlinesTime diffgr:id="AirlinesTime14" msdata:rowOrder="13" diffgr:hasChanges="inserted">
<Company><div class="pubFlights_8c">东星航空有限公司</div></Company>
<AirlineCode>8C8288</AirlineCode>
<StartDrome>浦东国际机场</StartDrome>
<ArriveDrome>天河机场</ArriveDrome>
<StartTime>22:30</StartTime>
<ArriveTime>23:50</ArriveTime>
<Mode>JET</Mode>
<AirlineStop>0</AirlineStop>
<Week>123456日</Week>
</AirlinesTime>
</Airlines>
</diffgr:diffgram>
</DataSet>
0 请登录后投票
   发表时间:2008-04-02  
schema验证,我不知道该如何解析,下面的部分,我可以试一下,写好了,我再给你发过去吧!
0 请登录后投票
   发表时间:2008-04-02  
===============简单的解析,就这样了,不过不知道,你想要的是什么效果?=============
import java.io.FileNotFoundException;
import java.io.StringReader;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.xml.sax.InputSource;

public class XmlToString {
private Document itsDom = null;
private Element itsRoot = null;
/**
* Jdom解析资源文件,并反回成字符串对象
*/
public String getString(String xml_path){
String xmlStr = "";
try{
SAXBuilder sb = new SAXBuilder();
StringReader sr = new StringReader(xml_path);
InputSource is = new InputSource(sr);
is.setEncoding("UTF-8");
itsDom = sb.build(is);
System.out.println(itsDom.toString());
itsRoot = itsDom.getRootElement();
System.out.println(itsRoot.getName());
}catch(FileNotFoundException ex){
ex.printStackTrace();
}catch(Exception ee){
ee.printStackTrace();
}
Element lines = itsRoot.getChild("Airlines");
List nodeList = lines.getChildren();
for (int i=0;i<nodeList.size();i++){
Element time = (Element)nodeList.get(i);
String id = time.getAttribute("diffgr:id").getValue();
String order = time.getAttribute("msdata:rowOrder").getValue();
String chage = time.getAttribute("diffgr:hasChanges").getValue();

Element company = time.getChild("Company");
Element div = company.getChild("div");
String clazz = div.getAttribute("class").getValue();
String div_value = div.getText();

Element code = time.getChild("AirlineCode");
String code_value = code.getText();

Element start = time.getChild("StartDrome");
String start_value = start.getText();

Element arrive = time.getChild("ArriveDrome");
String arrive_value = arrive.getText();

Element startTime = time.getChild("StartTime");
String st_value = startTime.getText();

Element arriveTime = time.getChild("ArriveTime");
String at_value = arriveTime.getText();

Element mode = time.getChild("Mode");
String mode_value = mode.getText();

Element stop = time.getChild("AirlineStop");
String stop_value = stop.getText();

Element week = time.getChild("Week");
String week_value = week.getText();
}
xmlStr = itsDom.toString();
return xmlStr;
}
}
0 请登录后投票
论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics