如何在java中从XML获取父元素属性和子值?

时间:2014-06-19 12:31:06

标签: java xml xml-parsing

我有一个XML文件,例如:

<parent value="first">
  <child>Bill</child>
</parent>

我想得到输出:value = first,child = Bill 这意味着我需要来自parrent元素的属性和来自子元素的值。

我试着这样做:

List<Str> obj = new ArrayList<Str>();
NodeList nList  = doc.getElementsByTagName("parent");
for (int i = 0; i < nList.getLength(); ++i) {
    Element attrElement = (Element) nList.item(i);
    NamedNodeMap map = attrElement.getAttributes();
       for (int j = 0; j < map.getLength(); j++) {
            Node attribute = map.item(j);
            Node eNode = nList.item(j);
            Element name = (Element) eNode;
            obj.add(new Str(attribute.getNodeValue(), name.getElementsByTagName("child").item(0).getTextContent()));
       }
    }

结果我的Str值为“null”。

1 个答案:

答案 0 :(得分:2)

像这样使用

      List<String> obj = new ArrayList<String>();
      NodeList nList  = doc.getElementsByTagName("parent");
      for (int i = 0; i < nList.getLength(); ++i) {
          NamedNodeMap map = nList.item(i).getAttributes();
             for (int j = 0; j < map.getLength(); j++) {
                  Node attribute = map.item(j);
                  Node eNode = nList.item(i); // Use i value here that is the issue. 
                  Element name = (Element) eNode;
                  obj.add(new String("Value = "+attribute.getNodeValue() + ",Child=" + 
                      name.getElementsByTagName("child").item(0).getTextContent()));
             }
          }

添加一个外部元素,适用于多个标记

<xml><parent value=first> 
    <child>Bill</child></parent> <parent value=second> <child>Steve</child>
</parent></xml>