2012-09-02 140 views
-3

嘿,我想閱讀和使用Java編寫XML代碼,所以我google'd如何做到這一點,但我發現,只有發動機的誰可以閱讀真正的輕鬆XML代碼如用java讀取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> 

但我想了解更多advance'd如:

<?xml version="1.0" encoding="UTF-8"?> 
<package> 
    <template name="store_avatars"> 

     <!-- UI validation for this file --> 
     <panel noclick="1" onload="CreateBool('ui_avatars_package_loaded', true);"/> 

     <!-- Female Pyromancer --> 
     <instance name="altAvatarPreviewPanel" 
      heroEntryID="1" 
      id="15" 
      product="Hero_Pyromancer.Female" 
      definition="/heroes/pyromancer" 
      heroName="Hero_Pyromancer" 
      hero_icon_path="/heroes/pyromancer/icon.tga" 
      hasvoice="true" 
      hasmodel="true" 
      hastexture="true" 
      hassounds="true" 
      hasanimations="true" 
      haseffects="false" 
     /> 

     <!-- Sexy Moon Queen --> 
     <instance name="altAvatarPreviewPanel" 
      heroEntryID="2" 
      id="16" 
      product="Hero_Krixi.Sexy" 
      definition="/heroes/krixi" 
      heroName="Hero_Krixi" 
      hero_icon_path="/heroes/krixi/icons/hero.tga" 
      hasvoice="false" 
      hasmodel="true" 
      hastexture="true" 
      hasanimations="true" 
      haseffects="false" 
     /> 
    </template> 
</package> 

所以我繼續做我自己的類此,

package Lindholm.languages; 

import java.util.Vector; 

import Lindholm.LLException; 
import Lindholm.LLString; 
import Lindholm.com.LLProperty; 

public class Xml { 
    //STATIC variables; 

    //Variables; 
    private Tag tag; 
    //Setup; 

    //Constructor; 
    public Xml(String xml) { 
     int index1; 

     //First removing all the comments so they dont' disturb the decoding; 
     index1 = 0; 
     while((index1 = xml.indexOf("<!--",index1)) != -1) { 
      int index2; 

      if((index2 = xml.indexOf("-->",index1)) != -1) { 
       String comment = xml.substring(index1,index2+"-->".length()); 
       xml = LLString.replace(xml,comment,"",1); 
      } 
      else { 
       try { 
        throw new Exception("Invail xml code, missing \"-->\"."); 
       } catch (Exception e) { 
        new LLException(e); 
       } 
      } 
     } 

     //replacing all "/>" cancelings to "</[abc]>"; 
     index1 = 0; 
     while((index1 = xml.indexOf("/>",0)) != -1) { 
      int index2; 

      String revstr = LLString.reverse(xml.substring(0,index1+"/>".length())); 
      index2 = revstr.indexOf("<",0); 
      index2 = revstr.length()-index2; 
      String name = xml.substring(index2,index1).split("\\s")[0]; 

      xml = LLString.replace(xml,"/>","></"+name+">",1); 
     } 

     //Adding index's to all tags which will make the decoding easier. 
     index1 = 0; 
     int n = 0; 
     Vector<Integer> openings = new Vector<Integer>(); 
     while(true) { 
      int index0 = index1; 
      int index2; 
      n++; 

      index1 = xml.indexOf("<",index0); 
      index2 = xml.indexOf("</",index0); 
      if(index1 != -1) { 
       index1 += "<".length(); 
      } 

      if(index1 != -1 && (index1 < index2 || index2 == -1)) { 
       xml = xml.substring(0,index1)+n+"-"+xml.substring(index1); 
       openings.add(n); 
       index1 += (n+"-").length(); 
      } 
      else if(index2 != -1 && (index2 < index1 || index1 == -1)) { 
       xml = xml.substring(0,index2+"</".length())+openings.get(openings.size()-1)+"-"+xml.substring(index2+"</".length()); 
       index1 += (openings.get(openings.size()-1)+"-").length(); 
       openings.remove(openings.size()-1); 
      } 
      else { 
       break; 
      } 
     } 

     //Now let's decode it!!! 
     xml = xml+"</1-?xml>"; 
     tag = readTag(xml,"1-?xml"); 
    } 
    //Set; 

    //Get; 
    public Tag getTag() { 
     return tag; 
    } 

    //Add; 

    //Remove; 

    //Do; 

    //Other; 
    private Tag readTag(String xmltag,String tagname) { 
     int index1 = ("<"+tagname).length(); //subract 1 due the first index is 0! 
     int index2; 
     String body = xmltag.substring(xmltag.indexOf(">",0)+">".length(),xmltag.indexOf("</"+tagname,0)); 
     LLProperty properties; 
     Vector<Tag> children = new Vector<Tag>(); 

     index2 = xmltag.indexOf(">",index1); 
     String xmlproperties = xmltag.substring(index1,index2); 
     properties = readProperties(xmlproperties); 

     while((index1 = body.indexOf("<",0)) != -1) { 
      index2 = body.indexOf(">",index1); 
      String subtagname = body.substring(index1+"<".length(),index2).split("\\s")[0]; 

      index2 = body.indexOf("</"+subtagname,index1)+"</".length(); 
      index2 = body.indexOf(">",index2)+">".length(); 

      String subxmltag = body.substring(index1,index2); 
      body = LLString.replace(body,subxmltag,"",1); 

      children.add(readTag(subxmltag,subtagname)); 
     } 
     if(children.size() == 0) { 
      body = null; 
     } 
     tagname = tagname.split("-")[1]; 

     Tag tag = new Tag(tagname,body); 
     tag.setProperties(properties); 
     tag.setChildren(children); 
     return tag; 
    } 
    private LLProperty readProperties(String xmlproperties) { 
     LLProperty properties = new LLProperty(); 
     int index1 = 0; 
     int index2; 

     while(xmlproperties.substring(index1).contains("=")) { 
      index2 = xmlproperties.indexOf("=",index1); 
      String key = LLString.trimAll(xmlproperties.substring(index1,index2)); 
      key = key.trim(); 

      index1 = index2+"=".length(); 
      int squote = xmlproperties.indexOf("'",index1); 
      int dquote = xmlproperties.indexOf("\"",index1); 
      String quote = ""; 

      if(squote != -1 && (squote < dquote || dquote == -1)) { 
       quote = "'"; 
      } 
      else if(dquote != -1 && (dquote < squote || squote == -1)) { 
       quote = "\""; 
      } 
      else { 
       try { 
        throw new Exception("Invail xml code, missing parameters."); 
       } catch (Exception e) { 
        new LLException(e); 
       } 
      } 
      index1 = xmlproperties.indexOf(quote,index1)+quote.length(); 
      index2 = xmlproperties.indexOf(quote,index1); 
      String value = xmlproperties.substring(index1,index2); 

      properties.setProperty(key,value); 
      index1 = index2+quote.length(); 
     } 

     return properties; 
    } 
    public void print() { 
     String xml = ""; 
     for(int i = 0;i <= tag.getChildren()-1;i++) { 
      xml += printTag(tag.getChild(i),""); 
     } 
     xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+ 
       xml; 
     System.out.println(xml); 
    } 
    private String printTag(Tag tag,String height) { 
     String xml = height+"<"+tag.getTag(); 

     Object[] keys = tag.getProperties().stringPropertyNames().toArray(); 
     String prop = " "; 
     if(keys.length >= 5) { 
      prop = "\n"+height+" "; 
     } 

     for(int i = 0;i <= keys.length-1;i++) { 
      xml += prop+keys[i]+"=\""+tag.getProperties().getProperty(keys[i].toString())+"\""; 
     } 
     if(tag.getBody() == null) { 
      xml += "/>\n"; 
     } 
     else { 
      xml += LLString.replace(prop+">\n"," ","",1); 
      for(int i = 0;i <= tag.getChildren()-1;i++) { 
       xml += printTag(tag.getChild(i),height+" "); 
      } 
      xml += height+"</"+tag.getTag()+">\n"; 
     } 

     return xml; 
    } 
    //Implements; 

} 

和標籤

package Lindholm.languages; 

import java.util.Vector; 

import Lindholm.com.LLProperty; 

public class Tag { 
    //STATIC variables; 

    //Variables; 
    private String tag; 
    private String body; 
    private LLProperty properties; 
    private Vector<Tag> children = new Vector<Tag>(); 

    //Setup; 

    //Constructor; 
    public Tag(String name,String body) { 
     tag = name; 
     this.body = body; 
    } 
    //Set; 
    public void setProperties(LLProperty properties) { 
     this.properties = properties; 
    } 
    public void setChildren(Vector<Tag> children) { 
     this.children = children; 
    } 

    //Get; 
    public String getTag() { 
     return tag; 
    } 
    public String getBody() { 
     return body; 
    } 
    public LLProperty getProperties() { 
     return properties; 
    } 
    public int getChildren() { 
     return children.size(); 
    } 
    public Tag getChild(int index) { 
     return children.get(index); 
    } 
    public Tag getChildByTag(String tagname) { 
     for(int i = 0;i <= getChildren()-1;i++) { 
      if(getChild(i).getTag().equals(tagname)) { 
       return getChild(i); 
      } 
     } 
     return null; 
    } 
    public Tag getChildByTag(String tagname,int number) { 
     for(int i = 0;i <= getChildren()-1;i++) { 
      if(getChild(i).getTag().equals(tagname)) { 
       if(number == 0) { 
        return getChild(i); 
       } 
       else { 
        number--; 
       } 
      } 
     } 
     return null; 
    } 

    //Add; 
    public void addChild(Tag child) { 
     children.add(child); 
    } 

    //Remove; 

    //Do; 

    //Other; 

    //Implements; 

} 

現在我的問題是,它的速度慢得難以置信,有沒有其他方法可以實現我想要的?或者可能使其更快?,也許我的代碼是壞的?

+0

您使用哪個xml解析器來讀取xml文件 –

+1

如何看待JDOM(http://www.jdom.org/)或JAXB(http://www.oracle.com/technetwork/articles/javase/index-140168.html)? – micha

+1

我投票給JAXB。給它一個研究,你會沒有遺憾! –

回答

10
  1. 請不要在的任何情況下嘗試編寫自己的XML解析器。儘管從表面上看,XML看起來很簡單,但它實際上是一個非常複雜的標準,並且它會遺漏其中的一部分。如果您也在控制XML創建,那麼您可能會忽略它。但是,如果你是,爲什麼要使用XML呢?如果你不是,那麼爲系統/庫/供應商做好準備,以便突然使用你的自制解析器無法處理的XML高級功能。
  2. 有很多可用的開源解析器。現在甚至有一個內置到JDK中。您可以選擇將整個文檔讀入DOM結構的內存中,或者獲取事件流(SAX)。開源庫也允許其他技術,如XML Pull。

看:

+2

+1,但我建議使用Xerces的內置JAXP版本,而不是明確地下載它。另外,我相信XMLPull已經成爲JDK 1.6及更高版本中的StAX實現。 – kdgregory

1

你可以使用另一個XML解析器。我聽說VTD-XML是非常快的。

1

閱讀的Java XML文件可以很輕鬆的完成....

使用SAX分析器

2.使用DOM分析器

3。使用XML Pull Parsing