-3

ねえ、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>

しかし、次のようなより高度なものを読みたいと思います。

<?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;

}

今私の問題は、それが非常に遅いということです。私が望むことを達成する他の方法はありますか? または多分それを速くする方法?, 多分私のコードは悪いですか?

4

3 に答える 3

10
  1. いかなる状況においても、独自のXMLパーサーを作成しようとしないでください一見XMLは単純に見えますが、実際には非常に複雑な標準であり、その一部を見逃してしまいます。XMLの作成も制御している場合は、それを回避できる可能性があります。しかし、もしそうなら、なぜXMLを使用するのでしょうか。そうでない場合は、それを作成しているシステム/ライブラリ/ベンダーが、自作のパーサーでは処理できないXMLの高度な機能を突然使用する準備をしてください。
  2. 利用可能なオープンソースパーサーはたくさんあります。現在、JDKに組み込まれているものもあります。ドキュメント全体をDOM構造のメモリに読み込むか、イベントストリーム(SAX)を取得するかを選択できます。オープンソースライブラリでは、XMLプルなどの他のテクノロジも使用できます。

見る:

于 2012-09-02T11:26:29.063 に答える
1

別のXMLパーサーを使用できます。VTD-XMLは非常に高速だと聞きました。

于 2012-09-02T11:30:58.497 に答える
1

Java での XML ファイルの読み取りは、非常に簡単に行うことができます....

1.SAXパーサーを使用する

2.DOMパーサーを使用する

3.使用XML Pull Parsing

于 2012-09-02T13:08:00.390 に答える