从XML获取标记名称

时间:2013-12-23 10:02:56

标签: java xml

我有一些XML:

<Details>
    <name>sam</name>
    <age>18</age>
</Details>

使用以下代码,我可以阅读值sam18。我还需要检索元素名称nameage。我怎么得到它?

我目前的代码:

Element root = XMLDocument.getDocumentElement();
NodeList nodelist = root.getChildNodes();
String[] rowdata = new String[2];
for (int nodeIndex = 0; nodeIndex < nodelist.getLength(); nodeIndex++) { 
  Node node = nodelist.item(nodeIndex);
  for(int elementIndex=0; elementIndex<node.getChildNodes().getLength(); elementIndex++){ 
    rowdata[0] = node.getChildNodes().item(elementIndex).getNodeName().toString();
    rowdata[1] = node.getChildNodes().item(elementIndex).getTextContent();
    System.out.println(rowdata[0] + " - " + rowdata[1]);
  }
} 

1 个答案:

答案 0 :(得分:0)

以下代码演示了如何打印元素名称:

String xml = "<Details><name>sam</name><age>18</age></Details>";
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document xmlDocument = dBuilder.parse(new ByteArrayInputStream(xml
    .getBytes("US-ASCII")));

Element root = xmlDocument.getDocumentElement();
NodeList nodelist = root.getChildNodes();
String[] rowdata = new String[2];
for (int nodeIndex = 0; nodeIndex < nodelist.getLength(); nodeIndex++) {
  Node node = nodelist.item(nodeIndex);

  if (node.getNodeType() == Node.ELEMENT_NODE) {
    System.out.println(node.getNodeName()); // Here we can print the element name
  }

  for (int elementIndex = 0; elementIndex < node.getChildNodes()
      .getLength(); elementIndex++) {

    Node childNode = node.getChildNodes().item(elementIndex);
    rowdata[0] = childNode.getNodeName().toString();
    rowdata[1] = childNode.getTextContent();
    System.out.println(rowdata[0] + " - " + rowdata[1]);
  }
}

输出:

name
#text - sam
age
#text - 18