我在以下模式中有一个xml文件,其中包含一些Complex Empty Elements
(元素不包含内容,仅包含属性)。
<items>
<item id="0" name="a" />
<item id="1" name="b" />
</items>
我不敢解析它们的属性。到目前为止,这是我所做的:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(inputStream);
Element itemsElement = document.getDocumentElement();
if (itemsElement.getTagName().equals(TAG_ITEMS)) {
NodeList nodeList = itemsElement.getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
// process each item node
Node node = nodeList.item(i);
if (node.getNodeType() == Node.TEXT_NODE) { // Is this the right way?
Text text = (Text) node;
// Do stuff with attributes
}
}
}
我无法将这些Text
节点强制转换为Element
节点并获取属性,我无法使用getAttributes
-NPE从节点获取节点的属性NamedNodeMap attributes.getLength()
,也无法将其强制转换为Text
获取属性。如何解析属性?
您对内部节点的文本上下文不感兴趣,items
但对节点的属性感兴趣item
。您可以按照以下步骤操作:
//process each item node
Node node = nodeList.item(i);
if (node.getNodeName().equals("item")) {
NamedNodeMap attributes = node.getAttributes();
System.out.printf("id=%s, name=%s%n",
attributes.getNamedItem("id").getTextContent(),
attributes.getNamedItem("name").getTextContent());
}
这将打印:
id=0, name=a
id=1, name=b
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句