Java DOM xml无法获取子对象

Java DOM xml无法获取子对象,java,xml,parsing,dom,nodes,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"> &l

我的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>
但是当我期望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() );
        }
    }
}
import java.io.IOException;
导入javax.xml.parsers.DocumentBuilder;
导入javax.xml.parsers.DocumentBuilderFactory;
导入javax.xml.parsers.parserConfiguration异常;
导入org.w3c.dom.Document;
导入org.w3c.dom.Element;
导入org.w3c.dom.Node;
导入org.w3c.dom.NodeList;
导入org.xml.sax.SAXException;
公开课考试
{
公共静态void main(字符串[]args)
{
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
尝试
{
DocumentBuilder db=dbf.newDocumentBuilder();
对于(int i=1;i您需要在此处使用。您可以先使用
getNodeName()
(仅在调试版本中)以确保您位于正确的位置


getNodeValue()
如果手头的节点是一个元素,则返回
null
。有一个表描述了每个可能上下文中
getNode*
的结果。

可能第一个子节点不是您认为的那样。这在XML中很重要,而且第一个子节点可能实际上是一个文本节点

如果有一个类型,您可以迭代所有检查节点类型的子节点,以获得实际元素的句柄

编辑:这将打印您要查找的值。它将在元素节点上进行筛选,然后在每个元素节点的第一个子节点(包含文本的节点)上进行筛选

NodeList NodeList=n.getChildNodes();
对于(int j=0;j
另外,正如@Steve Townsend所正确编写的,如果您使用的是Java 1.5或更高版本,则可以使用而不是
childNode.getFirstChild().getNodeValue()

尝试调用

doc.getDocumentElement()
而不是

doc.getFirstChild()
NodeList NodeList=n.getChildNodes();
对于(int j=0;j
如果我要使用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);  

            }         

     }  

}
导入java.io.BufferedWriter;
导入java.io.File;
导入java.io.FileInputStream;
导入java.io.FileOutputStream;
导入java.io.IOException;
导入java.io.OutputStreamWriter;
导入javax.xml.parsers.DocumentBuilder;
导入javax.xml.parsers.DocumentBuilderFactory;
导入org.w3c.dom.Document;
导入org.w3c.dom.Node;
导入org.w3c.dom.NodeList;
公共类RecDOMP{
公共静态void main(字符串[]args)引发异常{
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
dbf.setValidating(false);
DocumentBuilder db=dbf.newDocumentBuilder();
//用输入xml路径替换以下路径
Document doc=db.parse(新文件inputstream(新文件(“D:\\ambuj\\input.xml”));
//用输出xml路径替换以下路径
File OutputDOM=新文件(“D:\\ambuj\\outapip1.txt”);
FileOutputStream fostream=新的FileOutputStream(OutputDOM);
OutputStreamWriter oswriter=新的OutputStreamWriter(fostream);
BufferedWriter bwriter=新的BufferedWriter(oswriter);
//如果文件不存在,则创建它
如果(!OutputDOM.exists()){
OutputDOM.createNewFile();}
快速访问(文档、b编写者);
bwriter.close();oswriter.close();fostream.close();
系统输出打印项次(“完成”);
}
公共静态void visitRecursive(节点节点,BufferedWriter bw)引发IOException{
//获取所有子节点
NodeList list=node.getChildNodes();

对于(int i=0;i执行此操作时:
Node n=doc.getFirstChild();System.out.println(n.getTextContent())
我得到了:1falsefalsefalse…,似乎它得到了一切。我如何得到每一个单独的片段?@Raptrex-这是子节点的连接内容,看起来您的元素级别太高了。根据我的编辑,使用
getNodeName
进行验证。我从getNodeName获得了#文档,确认您需要d来深入了解感兴趣的元素。
Node n=doc.getDocumentElement();System.out.println(n.getTextContent());
我试过了,但仍然得到1FalseFalseFalseFalse…,而我所需要的只是遍历doc.getDocumentElement()的每个子级的单独1loop,然后在每个子级调用n.getFirstChild().getNodeValue()获取其文本。
doc.getFirstChild()
 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());
      }
  }   
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);  

            }         

     }  

}