假设我有一个 xml 标签,例如:
<test val="val1 ">Test XML</test>
每当文件中出现标记时,我想解析值“val1” <test>
,以便我可以将其保存到数组中。
您可以从文件中加载 XML 并选择所有带有标签名称的元素test
并从中提取属性值。
基本上:
doc.getElementsByTagName("test")
为了选择所有"test"
元素,并且对于找到的每个元素,您可以选择其名为"val"
with的属性,node.getAttributes().getNamedItem("val")
并且从该属性中选择,如果不为 null,则仅getTextContent()
获取其文本内容。
示例代码可能类似于:
// temporary result list just to store the values found
ArrayList<String> result = new ArrayList<String>();
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document doc = documentBuilder.parse(new ByteArrayInputStream("<document><test val=\"val1\">Test XML</test><test val=\"val2\">Test XML</test><test val=\"val3\">Test XML</test></document>".getBytes()));
// you could use something like: documentBuilder.parse(new FileInputStream("fileName.ext")); instead
// get test nodes and iterate over it checking test attribute
NodeList elements = doc.getElementsByTagName("test");
for (int i = 0; i < elements.getLength(); i++) {
Node node = elements.item(i);
Node attribute = node.getAttributes().getNamedItem("val");
if (attribute != null) {
result.add(attribute.getTextContent());
}
}
// get result values in a string array (if collection is preferred use result instead)
String[] array = result.toArray(new String[] {});
// just print it in a readable format
System.out.println(Arrays.toString(array));
这将打印:
[val1, val2, val3]