有一个重复标记的xml,像这样:
<abc:Body>
<abc:AssyData>
<abc:Order>1</abc:Order>
<abc:Name>A</abc:Name>
</abc:AssyData>
<abc:AssyData>
<abc:Order>2</abc:Order>
<abc:Name>B</abc:Name>
</abc:AssyData>
<abc:AssyData>
<abc:Order>3</abc:Order>
<abc:Name>C</abc:Name>
</abc:AssyData>
</abc:Body>
需要解析abc:Order和abc:Name的每个值并将其放入List中。目前,我的解析器只获取第一个值。下面是代码:
String order = null;
String name = null;
List<String> orders = new ArrayList<String>()
List<String> names = new ArrayList<String>()
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
dbf.setFeature(XML.Constants.FEATURE_SECURE_PROCESSING, true);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new File(IDOC));//IDOC это мой XML на диске
doc.getDocumentElement().normalize();
NodeList list = doc.getElementsByTagName("abc:Body");
for (int temp = 0; temp < list.getLength(); temp++) {
Node node = list.item(temp);
if(node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
orders.add(element.getElementsByTagName("abc:Order").item(0).getTextContext());
names.add(element.getElementsByTagName("abc:Name").item(0).getTextContext());
}
}
} catch ......
System out println(orders);
System out println(names);
输出:
List<String> orders = [1]
List<String> names = [A]
你需要通过标签获得所有元素的所有值并将它们写入表格,将是:
List<String> orders = [1,2,3]
List<String> names = [A,B,C]
Please help (java ee 5)
方法getElementByTagName不存在)我使用getElementsByTagName,它没有帮助
orders.add (element.getElementsByTagName("abc: Order") .item (0) .getTextContext ());names.add (element.getElementsByTagName("abc: Name") .item (0) .getTextContext ());
要获取重复标记的所有值,需要循环遍历"AssyData"的NodeList。元素,而不是只取第一个元素。你可以这样修改你的代码:
String order = null;
String name = null;
List<String> orders = new ArrayList<String>();
List<String> names = new ArrayList<String>();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
dbf.setFeature(XML.Constants.FEATURE_SECURE_PROCESSING, true);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new File(IDOC));//IDOC это мой XML на диске
doc.getDocumentElement().normalize();
NodeList list = doc.getElementsByTagName("abc:AssyData");
for (int temp = 0; temp < list.getLength(); temp++) {
Node node = list.item(temp);
if(node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
orders.add(element.getElementsByTagName("abc:Order").item(0).getTextContent());
names.add(element.getElementsByTagName("abc:Name").item(0).getTextContent());
}
}
} catch ......
System.out.println(orders);
System.out.println(names);
在修改后的代码中,我们使用getElementsByTagName而不是getElementByTagName来获取具有指定标记名的所有元素。然后,循环遍历"assydata"的NodeList。元素,并添加"abc:Order"one_answers"abc: Name"到各自的列表
这应该会产生期望的输出:
List<String> orders = [1, 2, 3]
List<String> names = [A, B, C]