2012-03-28 8 views
1

id1 & id2にアクセスするには、XMLのすべての値を繰り返します。id1またはid2という名前のタグが見つかると、その値を変数に読み込みます。 id1 & id2の値を読み取るより良い方法はありますか?XMLの値にアクセスする方法

<begin> 
    <total>1</total> 
    <values> 
    <factor> 
     <base>test</base> 
     <id1>id1</id1> 
     <id2>id2</id2> 
     <val>val2</val> 
     <newval>val1</newval> 
    </factor> 
    </values> 
</begin> 
+0

を、[XPathの](http://www.ibm.com/developerworks/library/x-javaxpathapi /)はあなたの友人です –

答えて

1

XPathを使用すると、Documentオブジェクトから値を直接抽出できます。あなたの場合、id1に到達するXPathは/begin/id1になります。

0

XPathをサポートするライブラリを使用します。 JDOMは現在私のお気に入りですが、そこにはたくさんのものがあります。

1

SAXパーサを使用し、 "id1"開始要素の後に出現するテキストをid1値として、 "id2"開始要素の後のテキストをid2値として格納します。例えば

:あなたはこのことのためにJDOMを使用することができます

public static List<String> getIds(InputStream xmlStream) throws ParserConfigurationException, SAXException, IOException { 
    final List<String> ids = new ArrayList<String>(); 
    SAXParserFactory factory = SAXParserFactory.newInstance(); 
    SAXParser saxParser = factory.newSAXParser(); 
    saxParser.parse(xmlStream, new DefaultHandler() { 
    boolean getChars = false; 
    public void startElement(String uri, String name, String qName, Attributes attrs) throws SAXException { 
     if ("id1".equalsIgnoreCase(qName)) getChars = true; 
     if ("id2".equalsIgnoreCase(qName)) getChars = true; 
    } 
    public void characters(char cs[], int start, int len) throws SAXException { 
     if (getChars) { 
     ids.add(new String(cs, start, len)); 
     getChars = false; 
     } 
    } 
    }); 
    return ids; 
} 
1

:あなたが興味を持って、すべてが特定の要素を照会している場合

import org.jdom.Document; 
import org.jdom.input.SAXBuilder; 

public class Test { 

    public static void main(String[] args) throws Exception{ 
     SAXBuilder builder = new SAXBuilder(); 
     Document doc = builder.build("test.xml"); 
     String id1 = doc.getRootElement().getChild("values").getChild("factor").getChild("id1").getValue(); 
     System.out.println(id1); 
     String id2 = doc.getRootElement().getChild("values").getChild("factor").getChild("id2").getValue(); 
     System.out.println(id2); 
    } 

} 
関連する問題