0

入力xmlなどのxmlでxml要素のソートを行う方法は、このようなものです Person A B Employee A B Person C D Employee C D

今、出力 Person A B Person C D Employee A B Employee C D のように xml をソートしたい

つまり、Person で始まるすべてのノードが最初に来て、次に Employee ノードが来ます...

今このようにしようとしています、

BufferedReader docInput = new BufferedReader(new InputStreamReader(inputStream));
BufferedWriter docOutput = new BufferedWriter(new OutputStreamWriter(outputStream));
StringBuffer insb = new StringBuffer();

String line = "", segment="";
String beginSegment = "";

Vector a=new Vector();
Vector b=new Vector();

Properties prop = System.getProperties();
String lineSeparator = prop.getProperty("line.separator");

int start=0,pos=0;

try
{
    while ((line = docInput.readLine()) != null)
    {
       line.replace(lineSeparator,"");      
       insb.append(line);
    }

    pos=insb.indexOf(":Recipient");
    pos=pos-15;
    pos=insb.indexOf("<",pos);
    beginSegment=insb.substring(0,pos);             
    System.out.println(" Begin "+beginSegment);
    insb=insb.replace(0,pos,"");

    while(insb.indexOf("Recipient>")>0)
    {
        pos=insb.indexOf("Recipient>");
        segment=insb.substring(0,pos+10);
        a.add(segment);
        segment="";
        insb=insb.replace(0,pos+10,"");
    }

    for(int y=0;y<b.size();y++)
        if(b.get(y).toString().contains("Employee>"))
        {
            a.add(b.get(y).toString());
            b.remove(y);
        }

    for(int y=0;y<a.size();y++)
        b.add(a.get(y).toString());

    b.add(0,beginSegment);
    b.add(insb.toString());

    for(int y=0;y<b.size();y++)
        docOutput.write(b.get(y).toString());

    docOutput.close();
    docInput.close();
}
4

1 に答える 1

0

compareTo メソッドを参考にしてみてはいかがでしょうか。

public int compareTo(String anotherString)

2 つの文字列を辞書順に比較します。この String オブジェクトが引数文字列の後に辞書式に続く場合、結果は正の整数になります。文字列が等しい場合、結果はゼロです。equals(Object) メソッドが true を返す場合、compareTo は正確に 0 を返します。

とにかく、XML パーサーを使用する必要があります。このように、オブジェクト リレーショナル マッピング機能を拡張する場合、つまり Person または Employee のインスタンスを取得する場合、これらのクラスに Comparable を実装して、People を好きなように並べ替えることができます。

于 2013-06-05T15:57:29.967 に答える