Java Api for parse the xml file

games.xml
<?xml version="1.0" ?>
<games>
 <game genre="rpg">XML Invaders</game>
 <game genre="rpg">A Node in the XPath</game>
 <game genre="rpg">XPath Races</game>
</games>

一、JDom
1.读xml

package org.test1;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.adapters.XercesDOMAdapter;
import org.jdom.input.DOMBuilder;

public class JDOMCreateExample
{
    private static DOMBuilder builder = null;
    public static void main(String[] args) throws FileNotFoundException, IOException, JDOMException
    {
        XercesDOMAdapter xercAdapter = new XercesDOMAdapter();
        org.w3c.dom.Document w3Dom = xercAdapter.getDocument(
                 new FileInputStream( "games.xml"), false );
       
        builder = new DOMBuilder("org.jdom.adapters.XercesDOMAdapter");
        Document doc = builder.build( w3Dom );
    
        List childs =  doc.getRootElement().getChildren( "game" );
        Iterator itr = childs.iterator();
        while( itr.hasNext() )
        {
            Element child = (Element) itr.next();
            System.out.println( child.getName() + " = " + child.getText() );
            System.out.println( child.getAttributeValue("genre") );
        }
    }
}
结果显示:
game = XML Invaders
rpg
game = A Node in the XPath
rpg
game = XPath Races
rpg

2.写xml
package org.test2;

import java.io.IOException;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.XMLOutputter;


public class JDOMCreateExample2
{

    public static void main(String[] args) throws IOException
    {
        Document doc = new Document( new Element("games") );
        Element newGame = new Element( "game" ).setText( "Final Fantasy" );
        doc.getRootElement().addContent( newGame );
       
        newGame.setAttribute( "genre", "rpg" );
        XMLOutputter domstream = new XMLOutputter();
        domstream.output( doc, System.out );
    }
}
结果显示:
<?xml version="1.0" encoding="UTF-8"?>
<games><game genre="rpg">Final Fantasy</game></games>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值