Java DOM xml无法得到孩子

时间:2011-06-22 18:20:22

标签: java xml parsing dom nodes

我的XML看起来像这样:

<ConnProf ConnProfID="1111">
  <ConnNum>1</ConnNum>
  <IsMSPA>false</IsMSPA>
  <IsArray>false</IsArray>
  <IsDDOR>false</IsDDOR>

  <Subsystem SSID="2222"ConnProfID="3333">
    <SSName>AA</SSName>
    <GenericSSName>AA</GenericSSName>
    <ConnFuncAddr>aaa</ConnFuncAddr>
    <DSSNum>22</DSSNum>
    <isRemoved>false</isRemoved>
  </Subsystem>

  <Subsystem SSID="4444" ConnProfID="5555">
    <SSName>BBBB</SSName>
    <GenericSSName>BB</GenericSSName>
    <ConnFuncAddr>bbbbbb</ConnFuncAddr>
    <DSSNum>44</DSSNum>
    <isRemoved>false</isRemoved>
  </Subsystem>

我无法获得ConnNum,IsMSPA,IsArray和IsDDOR。 我试着用ConnNum:

//get ConnNum
                Node n = doc.getFirstChild();
                if (n.hasChildNodes())
                    System.out.println(n.getFirstChild().getNodeValue());
                else 
                    System.out.println(n.getNodeValue());

但是当我期待1时它只返回null。

import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class test 
{
    public static void main(String[] args)
    {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

        try 
        {
            DocumentBuilder db = dbf.newDocumentBuilder();

            for (int i = 1; i <= 8; i++)
            {
                Document doc = db.parse("file" + i + ".xml");

                doc.getDocumentElement ().normalize ();
                System.out.println ("Root element of the doc is " + doc.getDocumentElement().getNodeName());

                //get ConnNum
                Node n = doc.getFirstChild();
                if (n.hasChildNodes())
                    System.out.println(n.getFirstChild().getNodeValue());
                else 
                    System.out.println(n.getNodeValue());

                NodeList listOfSubsystems = doc.getElementsByTagName("Subsystem");
                int totalSubsystems = listOfSubsystems.getLength();

                if (totalSubsystems == 0)
                    continue;
                else
                {
                    System.out.println("Total number of subsystems : " + totalSubsystems + "\n");

                    Dish dish = new Dish();

                    for(int s=0; s < listOfSubsystems.getLength() ; s++)
                    {
                        Node firstPersonNode = listOfSubsystems.item(s);

                        if(firstPersonNode.getNodeType() == Node.ELEMENT_NODE)
                        {
                            Element firstPersonElement = (Element)firstPersonNode;

                            printElement(firstPersonElement, "SSName");
                            printElement(firstPersonElement, "GenericSSName");
                            printElement(firstPersonElement, "ConnFuncAddr");
                            printElement(firstPersonElement, "DSSNum");
                            printElement(firstPersonElement, "SCNum");
                            printElement(firstPersonElement, "SCAcronym");
                            printElement(firstPersonElement, "PassNum");
                            printElement(firstPersonElement, "FzCode");
                            printElement(firstPersonElement, "isRemoved");
                            System.out.println("------------------");
                        }
                    }
                    System.out.println("\n==============================");
                }

            }
        }
        catch(ParserConfigurationException pce) 
        {
            pce.printStackTrace();
        }
        catch(SAXException se) 
        {
            se.printStackTrace();
        }
        catch(IOException ioe) 
        {
            ioe.printStackTrace();
        }
    }   

    public static void printElement(Element a, String name)
    {
        NodeList elementList = a.getElementsByTagName(name);
        Element b = (Element)elementList.item(0);

        if (b != null)
        {
            NodeList list = b.getChildNodes();
            System.out.println( ((Node)list.item(0)).getNodeValue().trim() );
        }
    }
}

5 个答案:

答案 0 :(得分:13)

也许第一个孩子不是你想象的那样。 Whitespace在XML中很重要,firstChild可能实际上是 text 节点。

Nodes有一个类型,你可以迭代所有检查 Element 节点类型的子节点来获取实际元素的句柄。

编辑:打印您所追求的值。它在 Element 节点上进行过滤,然后对每个节点的第一个子节点(包含文本的节点)进行过滤。

NodeList nodeList = n.getChildNodes();
for (int j = 0; j < nodeList.getLength(); j++) {
    Node childNode = nodeList.item(j);
    if (childNode.getNodeType() == Node.ELEMENT_NODE) {
        System.out.println(childNode.getNodeName() + " " + childNode.getFirstChild().getNodeValue());
    }
}

此外,正如@Steve Townsend正确写道,如果您使用的是Java 1.5或更高版本,则可以使用getTextContent()而不是childNode.getFirstChild().getNodeValue()

答案 1 :(得分:5)

 NodeList nodeList = n.getChildNodes();
 for (int j = 0; j < nodeList.getLength(); j++) {
     Node childNode = nodeList.item(j);
     if (childNode instanceof Element) {
          Element childElement = (Element) childNode;
          System.out.println(childElement.getNodeName() + " " +     childElement.getFirstChild().getNodeValue());
      }
  }   

答案 2 :(得分:2)

您需要在此处使用getTextContent()。您可以先使用getNodeName()(仅限调试版)以确保您处于正确的位置。

如果手头的节点是元素,则

getNodeValue()返回null。有一个表here,用于描述每个可能上下文中getNode*的结果。

答案 3 :(得分:0)

尝试拨打

doc.getDocumentElement()

而不是

doc.getFirstChild()

答案 4 :(得分:0)

如果我打算使用DOM解析器。我总是喜欢以下方法,因为我们不需要知道xml的每个标记并逐个打印它们。

import java.io.BufferedWriter;
import java.io.File;  
import java.io.FileInputStream;  
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

 import javax.xml.parsers.DocumentBuilder;  
 import javax.xml.parsers.DocumentBuilderFactory;  
 import org.w3c.dom.Document;  
 import org.w3c.dom.Node;  
 import org.w3c.dom.NodeList;  



public class RecDOMP {


public static void main(String[] args) throws Exception{
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();  
        dbf.setValidating(false); 
        DocumentBuilder db = dbf.newDocumentBuilder();   

// replace following  path with your input xml path  
         Document doc = db.parse(new FileInputStream(new File  ("D:\\ambuj\\input.xml")));  

// replace following  path with your output xml path 
         File OutputDOM = new File("D:\\ambuj\\outapip1.txt");
            FileOutputStream fostream = new FileOutputStream(OutputDOM);
            OutputStreamWriter oswriter = new OutputStreamWriter (fostream);
            BufferedWriter bwriter = new BufferedWriter(oswriter);

            // if file doesnt exists, then create it
            if (!OutputDOM.exists()) {
                OutputDOM.createNewFile();}


            visitRecursively(doc,bwriter);
            bwriter.close(); oswriter.close(); fostream.close();

            System.out.println("Done");
}
public static void visitRecursively(Node node, BufferedWriter bw) throws IOException{  

             // get all child nodes  
         NodeList list = node.getChildNodes();                                  
         for (int i=0; i<list.getLength(); i++) {          
                 // get child node              
       Node childNode = list.item(i);  
       if (childNode.getNodeType() == Node.TEXT_NODE)
       {
   //System.out.println("Found Node: " + childNode.getNodeName()           
    //   + " - with value: " + childNode.getNodeValue()+" Node type:"+childNode.getNodeType()); 

   String nodeValue= childNode.getNodeValue();
   nodeValue=nodeValue.replace("\n","").replaceAll("\\s","");
   if (!nodeValue.isEmpty())
   {
       System.out.println(nodeValue);
       bw.write(nodeValue);
       bw.newLine();
   }
       }
       visitRecursively(childNode,bw);  

            }         

     }  

}