有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我有一个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()));
       }
    }

结果我得到了带有“null”值的Str


共 (1) 个答案

  1. # 1 楼答案

    像这样使用

          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>