2011-07-02 6 views
0

私は以下のような文字列を持っています。文字列中の特定の値を取得するための操作

は私がstring.iとして取得しています上記のxmlが原因パフォーマンスissue.Iに解析を使用しないように頼まれた
<employees> 
<emp> 
<name>yaakobu</name> 
<sal>$20000</sal> 
<designation>Manager</designation> 
</emp> 

<emp> 
<name>daaniyelu</name> 
<sal>$2000</sal> 
<designation>Operator</designation> 
</emp> 

<emp> 
<name>paadam</name> 
<sal>$7000</sal> 
<designation>Engineer</designation> 
</emp> 
</employees> 

は私を提供operation.Please Javaの文字列を使用して、第2の従業員の給与($ 2000)を取得する必要がありますいくつかのポインタ。

あなたのお手伝いがあります。

+2

xmlパーサを使用するAFAIKはパフォーマンスを低下させません。私が間違っている場合は、私に知らせてください。 –

+4

_「パフォーマンスの問題のために構文解析を使用しない」_何の意味もありません! –

+0

入力の従業員の名前または位置によってXMLノードを探していますか? – Bohemian

答えて

2

あなたの文字列はxmlです。 xmlからデータを抽出するためにregexやその他の文字列操作を使用するのは魅力的かもしれませんが、それは悪いことです。

代わりにXMLパーサーを使用する必要があります。

+0

+1 - 健全なアドバイス。 –

0

xmlパーサーを使用するとパフォーマンス上の問題が発生するのではないかと疑いがありますが、文字列解析で実行したい場合はstr.indexOf("<sal>", str.indexOf("<sal>") + 5);を使用してください。

+0

開始時に 'emp'がコメントされている場合、これは機能しません。 –

+0

@Bart Kiers - あなたは正しいです、私の投稿はOPのためのちょうど出発です。 –

0

xstreamを使用する場合があります http://x-stream.github.io/ オブジェクト構造にxmlを入れてそこから取得します。

、:)

0

...あなたは自分自身を解析したくない場合は

これを使用することは非常に簡単です、あなたのオブジェクトにアンマーシャリング文字列のための使用XMLパーサーやJAXB APIをサンプルをチェックこの方法でもやり遂げることができます。

private static Object getObject(String yourXml) throws Exception { 



    JAXBContext jcUnmarshal = null; 

    Unmarshaller unmarshal = null; 

    javax.xml.stream.XMLStreamReader rdr = null; 



    //Object obj = null; 

    try { 



     jcUnmarshal = JAXBContext.newInstance("com.test.dto"); 

     unmarshal = jcUnmarshal.createUnmarshaller(); 

     rdr = javax.xml.stream.XMLInputFactory.newInstance().createXMLStreamReader(new StringReader(yourXml)); 



     //obj = (Object) unmarshal.unmarshal(rdr); 

     return (Object) unmarshal.unmarshal(rdr); 



    } catch (JAXBException jaxbException) { 

     jaxbException.printStackTrace(); 

     log.error(jaxbException); 

     throw new ServiceException(jaxbException.getMessage()); 

    } 

    finally{ 

     jcUnmarshal = null; 

     unmarshal = null; 

     rdr.close(); 

     rdr = null; 

    } 



    //return obj; 



} 
2

あなたがこれはあなたの文字列操作を使用してやった後、次試してみる:

import org.w3c.dom.*; 
import javax.xml.parsers.*; 
import javax.xml.xpath.*; 

public class Main { 
    public static void main(String[] args) throws Exception { 
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); 
    domFactory.setNamespaceAware(true); 
    DocumentBuilder builder = domFactory.newDocumentBuilder(); 
    Document doc = builder.parse("test.xml"); 
    XPath xpath = XPathFactory.newInstance().newXPath(); 

    // get the salary from the employee at index 1 
    XPathExpression expr = xpath.compile("//emp[1]/sal"); 
    Object salary = expr.evaluate(doc, XPathConstants.STRING); 
    System.out.println(salary); 
    } 
} 

いるはず出力:

$20000 

私はそれがされる保証はありませんよより速く、しかしそれは私が思うほど大きくは変わらないでしょう。そして、このようにすることは、indexOf(...)substring(...)コールでこれを行うよりはるかに脆弱になります。

関連する問題