34

我想遍历一段 XML 打印中的所有元素。我的问题是我在staff1标签之后不断收到一个空指针异常,即john 465456433 gmail1 area1 city1

这是我的 Java 代码,用于打印 xml 文件中的所有元素:

File fXmlFile = new File("file.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);

doc.getDocumentElement().normalize();

System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

NodeList nList = doc.getElementsByTagName("*");

System.out.println("----------------------------");

Node n=null;
Element eElement=null;

for (int i = 0; i < nList.getLength(); i++) {           
  System.out.println(nList.getLength());     
  n= nList.item(i);                            
  System.out.println("\nCurrent Element :" + n.getNodeName());


  if (n.getNodeType() == Node.ELEMENT_NODE) {
    eElement = (Element) n.getChildNodes();
    System.out.println("\nCurrent Element :" + n.getNodeName());
    name = eElement.getElementsByTagName("name").item(i).getTextContent(); //here throws null pointer exception after printing staff1 tag
    phone = eElement.getElementsByTagName("phone").item(i).getTextContent();
    email = eElement.getElementsByTagName("email").item(i).getTextContent();
    area = eElement.getElementsByTagName("area").item(i).getTextContent();
    city = eElement.getElementsByTagName("city").item(i).getTextContent();
  }
  n.getNextSibling();
}

XML 文件:

<?xml version="1.0"?>
<company>
  <staff1>
    <name>john</name>
    <phone>465456433</phone>
    <email>gmail1</email>
    <area>area1</area>
    <city>city1</city>
  </staff1>
  <staff2>
    <name>mary</name>
    <phone>4655556433</phone>
    <email>gmail2</email>
    <area>area2</area>
    <city>city2</city>
  </staff2>
  <staff3>
    <name>furvi</name>
    <phone>4655433</phone>
    <email>gmail3</email>
    <area>area3</area>
    <city>city3</city>
  </staff3>
</company>

预期输出:

john
465456433
gmail1
area1
city1
mary
4655556433
gmail2
area2
city2
furvi
4655433
gmail3
area3
city3
4

4 回答 4

74
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document dom = db.parse("file.xml");
    Element docEle = dom.getDocumentElement();
    NodeList nl = docEle.getChildNodes();
    int length = nl.getLength();
    for (int i = 0; i < length; i++) {
        if (nl.item(i).getNodeType() == Node.ELEMENT_NODE) {
            Element el = (Element) nl.item(i);
            if (el.getNodeName().contains("staff")) {
                String name = el.getElementsByTagName("name").item(0).getTextContent();
                String phone = el.getElementsByTagName("phone").item(0).getTextContent();
                String email = el.getElementsByTagName("email").item(0).getTextContent();
                String area = el.getElementsByTagName("area").item(0).getTextContent();
                String city = el.getElementsByTagName("city").item(0).getTextContent();
            }
        }
    }

遍历所有子节点并nl.item(i).getNodeType() == Node.ELEMENT_NODE用于过滤掉文本节点。如果 XML 中没有其他内容,那么剩下的就是人员节点。

对于东西下的每个节点(姓名、电话、电子邮件、地区、城市)

 el.getElementsByTagName("name").item(0).getTextContent(); 

el.getElementsByTagName("name")将提取东西下的“名称”节点, .item(0)将获得第一个节点并.getTextContent()获得其中的文本内容。

编辑: 因为我们有杰克逊,我会以不同的方式做到这一点。为对象定义一个 pojo:

public class Staff {
    private String name;
    private String phone;
    private String email;
    private String area;
    private String city;
...getters setters
}

然后使用杰克逊:

    JsonNode root = new XmlMapper().readTree(xml.getBytes());
    ObjectMapper mapper = new ObjectMapper();
    root.forEach(node -> consume(node, mapper));



private void consume(JsonNode node, ObjectMapper mapper) {
    try {
        Staff staff = mapper.treeToValue(node, Staff.class);
        //TODO your job with staff
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }
}
于 2013-01-28T16:48:50.520 回答
8
public class XMLParser {
   public static void main(String[] args){
      try {
         DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
         Document doc = dBuilder.parse(new File("xml input"));
         NodeList nl=doc.getDocumentElement().getChildNodes();

         for(int k=0;k<nl.getLength();k++){
             printTags((Node)nl.item(k));
         }
      } catch (Exception e) {/*err handling*/}
   }

   public static void printTags(Node nodes){
       if(nodes.hasChildNodes()  || nodes.getNodeType()!=3){
           System.out.println(nodes.getNodeName()+" : "+nodes.getTextContent());
           NodeList nl=nodes.getChildNodes();
           for(int j=0;j<nl.getLength();j++)printTags(nl.item(j));
       }
   }
}

递归循环并打印出文档中的所有 xml 子标签,以防您不必更改代码来处理 xml 中的动态更改,前提是它是格式良好的 xml。

于 2015-06-06T12:14:10.280 回答
3

这是使用 JDOM 循环遍历 XML 元素的另一种方法。

        List<Element> nodeNodes = inputNode.getChildren();
        if (nodeNodes != null) {
            for (Element nodeNode : nodeNodes) {
                List<Element> elements = nodeNode.getChildren(elementName);
                if (elements != null) {
                    elements.size();
                    nodeNodes.removeAll(elements);
                }
            }
于 2016-06-10T13:36:37.640 回答
0
NodeList listaHijos = docEle.getChildNodes();
        listaHijos = listaHijos.item(2).getChildNodes();
        for (int i = 0; i < listaHijos.getLength(); i++) {
            eElement = (Element) listaHijos.item(i);
            n2 = eElement.getChildNodes();
            for (int j = 0; j < n2.getLength(); j++) {
                System.out.println("elem:" + n2.item(j).getNodeName() + " :" + n2.item(j).getTextContent() + "j" + j);
                if (n2.item(j).getNodeName().equals("detallesAdicionales")) {                                                                        
                    eElement = (Element) n2.item(j);
                    n6 = eElement.getChildNodes();
                    System.out.println("todo: " + n6.item(0).getAttributes().item(0) + n6.item(0).getAttributes().item(1));                        
                    System.out.println("todo2: " + n6.item(1).getAttributes().item(0) + n6.item(1).getAttributes().item(1));                        
                    System.out.println("todo3: " + n6.item(2).getAttributes().item(0) + n6.item(2).getAttributes().item(1));                        
                    System.out.println("nombre: " + n6.item(0).getAttributes().item(0).getTextContent());
                    System.out.println("valor: " + n6.item(0).getAttributes().item(1).getTextContent());
                }
            }
        }
于 2021-10-07T14:24:25.753 回答