タグ<A>と<B>をそれぞれArrayListに詰め込みたい
だけなら以下のコードでいけます。
java
1import java.io.ByteArrayInputStream;
2import java.io.IOException;
3import java.nio.charset.StandardCharsets;
4import java.util.ArrayList;
5import java.util.List;
6
7import javax.xml.parsers.DocumentBuilder;
8import javax.xml.parsers.DocumentBuilderFactory;
9import javax.xml.parsers.ParserConfigurationException;
10
11import org.w3c.dom.Document;
12import org.w3c.dom.Element;
13import org.w3c.dom.NodeList;
14import org.xml.sax.SAXException;
15
16public class Main {
17
18 public static void main(String[] args) {
19 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
20 DocumentBuilder documentBuilder;
21 try {
22 documentBuilder = factory.newDocumentBuilder();
23
24 // Document document = documentBuilder.parse(XMLファイル); // 本来はファイルから
25 Document document = documentBuilder
26 .parse(new ByteArrayInputStream("<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?><Tags><A>7</A><A>9</A><A>7</A><A>9</A><A>7</A><A>9</A><B>0</B><B>5</B><B>3</B><B>0</B><B>0</B><B>0</B></Tags>".getBytes(StandardCharsets.UTF_8.name())));
27
28 Element root = document.getDocumentElement();
29 NodeList aTagNodeList = root.getElementsByTagName("A");
30 NodeList bTagNodeList = root.getElementsByTagName("B");
31
32 List<String> aTextList = new ArrayList<>();
33 List<String> bTextList = new ArrayList<>();
34
35 for (int i = 0; i < aTagNodeList.getLength(); i++) {
36 aTextList.add(aTagNodeList.item(i).getTextContent());
37 }
38 for (int i = 0; i < bTagNodeList.getLength(); i++) {
39 bTextList.add(bTagNodeList.item(i).getTextContent());
40 }
41
42 System.out.println(String.join(",", aTextList));
43 System.out.println(String.join(",", bTextList));
44
45 } catch (ParserConfigurationException | SAXException | IOException e) {
46 // TODO 自動生成された catch ブロック
47 e.printStackTrace();
48 }
49 }
50}
もし、
<A>というタグが続く限りArrayListにタグ<A>の要素を追加していく
というやり方じゃないとだめなのであれば、
root.getElementsByTagName
するのではなく、 Tagsタグを取得した後に、getChildNodes
してひとつひとつ順番に見ていってください。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。