java解析xml并从复杂的xml中检索子数据

时间:2014-03-28 09:36:47

标签: java xml file parsing dom

我正在尝试使用以下java代码解析xml文件。问题是当它从内部读取数据时我可以从每个地方检索数据数据,但是如果一个包下有多个项目,这意味着,虽然它不会检索父项下的所有孩子,你能帮忙吗?

 import java.io.File;
 import org.w3c.dom.*;
 import javax.xml.parsers.DocumentBuilderFactory;
 import javax.xml.parsers.DocumentBuilder;
 import org.xml.sax.SAXException;
 import org.xml.sax.SAXParseException; 
public class ReadAndPrintXMLFile{

public static void ReadXmlandParce(String filename){
try {

        DocumentBuilderFactory docBuilderFactory =  DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
        Document doc = docBuilder.parse (new File(filename));

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


        NodeList Messagend = doc.getElementsByTagName("IMessage");

        for(int s=0; s<Messagend.getLength() ; s++){


            Node MessageItemNode = Messagend.item(s);
            if(MessageItemNode.getNodeType() == Node.ELEMENT_NODE){


                Element MessageElement = (Element)MessageItemNode;

                //-------
                NodeList MessageNamend =  MessageElement.getElementsByTagName("IMessageName");
                Element MessageNameElement = (Element)MessageNamend.item(0);

                NodeList textMessageName = MessageNameElement.getChildNodes();
                System.out.println("MessageName : " + 
                       ((Node)textMessageName.item(0)).getNodeValue().trim());

                //-------
                NodeList MessageDatend = MessageElement.getElementsByTagName("IMessageDate");
                Element MessageDateElement = (Element)MessageDatend.item(0);

                NodeList textMessageDate = MessageDateElement.getChildNodes();
                System.out.println("MessageDate : " + 
                       ((Node)textMessageDate.item(0)).getNodeValue().trim());

                //----
                NodeList ServiceOrderednd = MessageElement.getElementsByTagName("IServiceOrderedType");
                Element ServiceOrderedElement = (Element)ServiceOrderednd.item(0);

                NodeList textServiceOrdered = ServiceOrderedElement.getChildNodes();
                System.out.println("ServiceOrdered : " + 
                       ((Node)textServiceOrdered.item(0)).getNodeValue().trim());

                //------     

                NodeList ServiceTypend = MessageElement.getElementsByTagName("IServiceType");
                Element ServiceTypeElement = (Element)ServiceTypend.item(0);

                NodeList textServiceType = ServiceTypeElement.getChildNodes();
                System.out.println("ServiceType : " + 
                       ((Node)textServiceType.item(0)).getNodeValue().trim());

                //------  

                NodeList SpecialInstructionsnd = MessageElement.getElementsByTagName("Instructions");
                Element SpecialInstructionsElement = (Element)SpecialInstructionsnd.item(0);

                NodeList textSpecialInstructions = SpecialInstructionsElement.getChildNodes();
                System.out.println("SpecialInstructions : " + 
                       ((Node)textSpecialInstructions.item(0)).getNodeValue().trim());

                //------  

                NodeList CompanyNamend = MessageElement.getElementsByTagName("CompanyName");
                Element CompanyNameElement = (Element)CompanyNamend.item(0);

                NodeList textCompanyName = CompanyNameElement.getChildNodes();
                System.out.println("CompanyName : " + 
                       ((Node)textCompanyName.item(0)).getNodeValue().trim());

                //------  



            }//end of if clause


        }//end of for loop with s var


        ///////////////////////////////////
        NodeList Consigneend = doc.getElementsByTagName("UConsignee");


        for(int j=0; j<Consigneend.getLength() ; j++){


            Node ConsigneeItemNode = Consigneend.item(j);
            if(ConsigneeItemNode.getNodeType() == Node.ELEMENT_NODE){


                Element ConsigneeElement = (Element)ConsigneeItemNode;

                //-------
                NodeList CompanyCodend = ConsigneeElement.getElementsByTagName("UCompanyCode");
                Element  CompanyCodeElement = (Element)CompanyCodend.item(0);

                NodeList textCompanyCode = CompanyCodeElement.getChildNodes();

                try{
                System.out.println("UCompanyCode : " +((Node)textCompanyCode.item(0)).getNodeValue().trim());
                }
                catch (NullPointerException err ) {
                    System.out.println ("UCompanyCode : empty");

                    }

                //-------
                NodeList CompanyNamend = ConsigneeElement.getElementsByTagName("UCompanyName");
                Element  CompanyNameElement = (Element)CompanyNamend.item(0);

                NodeList textCompanyName = CompanyNameElement.getChildNodes();
                System.out.println("CompanyName : " + 
                       ((Node)textCompanyName.item(0)).getNodeValue().trim());

                //----
                NodeList TaxNond = ConsigneeElement.getElementsByTagName("UTaxNo");
                Element TaxNoElement = (Element)TaxNond.item(0);

                NodeList textTaxNo= TaxNoElement.getChildNodes();
                System.out.println("TaxNo : " + 
                       ((Node)textTaxNo.item(0)).getNodeValue().trim());

                //------                     

                NodeList Street1nd = ConsigneeElement.getElementsByTagName("Street1");
                Element  Street1Element = (Element)Street1nd.item(0);

                NodeList textStreet1 = Street1Element.getChildNodes();
                try{
                System.out.println("Street1 : " + 
                       ((Node)textStreet1.item(0)).getNodeValue().trim());
                }
                catch (NullPointerException err ) {
                    System.out.println ("Street1 : empty");
                    }
                //----                    
                NodeList Street2nd = ConsigneeElement.getElementsByTagName("Street2");
                Element  Street2Element = (Element)Street2nd.item(0);

                NodeList textStreet2 = Street2Element.getChildNodes();
                try{
                System.out.println("Street2 : " + 
                       ((Node)textStreet2.item(0)).getNodeValue().trim());
                }
                catch (NullPointerException err ) {
                    System.out.println ("Street2 : empty");
                    }
                //----                    
                NodeList PostalCodend = ConsigneeElement.getElementsByTagName("PostalCode");
                Element  PostalCodeElement = (Element)PostalCodend.item(0);

                NodeList textPostalCode = PostalCodeElement.getChildNodes();
                try{
                System.out.println("PostalCode : " + 
                       ((Node)textPostalCode.item(0)).getNodeValue().trim());
                }
                catch (NullPointerException err ) {
                    System.out.println ("PostalCode : empty");
                    }
                //----
                NodeList CityNamend = ConsigneeElement.getElementsByTagName("CityName");
                Element  CityNameElement = (Element)CityNamend.item(0);

                NodeList textCityName = CityNameElement.getChildNodes();
                try{
                System.out.println("CityName : " + 
                       ((Node)textCityName.item(0)).getNodeValue().trim());
                }
                catch (NullPointerException err ) {
                    System.out.println ("CityName : empty");
                    }
                //----

                NodeList Countrynd = ConsigneeElement.getElementsByTagName("Country");
                Element  CountryElement = (Element)Countrynd.item(0);

                NodeList textCountry = CountryElement.getChildNodes();
                try{
                System.out.println("Country : " + 
                       ((Node)textCountry.item(0)).getNodeValue().trim());
                }
                catch (NullPointerException err ) {
                    System.out.println ("Country : Bos");
                    }
                //----

                NodeList TaxRegNond = ConsigneeElement.getElementsByTagName("TaxRegNo");
                Element  TaxRegNoElement = (Element)TaxRegNond.item(0);

                NodeList textTaxRegNo = TaxRegNoElement.getChildNodes();
                try{
                System.out.println("TaxRegNo : " + 
                       ((Node)textTaxRegNo.item(0)).getNodeValue().trim());
                }
                catch (NullPointerException err ) {
                    System.out.println ("TaxRegNo : empty");
                    }
                //----
                System.out.println ("+++++++++++++++++++++++++++");
                System.out.println ("Begin of Package");
                System.out.println ("+++++++++++++++++++++++++++");
                NodeList Packagend = doc.getElementsByTagName("CPackage");


                for(int k=0; k<Packagend.getLength() ; k++){

                    Node PackageItemNode = Packagend.item(k);
                    if(PackageItemNode.getNodeType() == Node.ELEMENT_NODE){


                        Element PackageElement = (Element)PackageItemNode;

                        //-------
                        NodeList PackageTypend = PackageElement.getElementsByTagName("CPackageType");
                        Element  PackageTypeElement = (Element)PackageTypend.item(0);
                        NodeList textPackageType = PackageTypeElement.getChildNodes();
                        try{
                        System.out.println("PackageType : " + 
                                ((Node)textPackageType.item(0)).getNodeValue().trim());
                        }
                        catch (NullPointerException err ) {
                            System.out.println ("PackageType : empty");
                            }
                        //-------
                        NodeList GrossWeightnd = PackageElement.getElementsByTagName("CGrossWeight");
                        Element  GrossWeightElement = (Element)GrossWeightnd.item(0);
                        NodeList textGrossWeight = GrossWeightElement.getChildNodes();
                        try{
                        System.out.println("GrossWeight : " + 
                                ((Node)textGrossWeight.item(0)).getNodeValue().trim());
                        }
                        catch (NullPointerException err ) {
                            System.out.println ("GrossWeight : empty");
                            }
                        //-------
                        NodeList Barcodend = PackageElement.getElementsByTagName("CBarcode");
                        Element  BarcodeElement = (Element)Barcodend.item(0);
                        NodeList textBarcode = BarcodeElement.getChildNodes();
                        try{
                        System.out.println("Barcode : " + 
                                ((Node)textBarcode.item(0)).getNodeValue().trim());
                        }
                        catch (NullPointerException err ) {
                            System.out.println ("Barcode : empty");

                            }
                        //-------

                        System.out.println ("+++++++++++++++++++++++++++");
                        System.out.println ("Begin of Item");
                        System.out.println ("+++++++++++++++++++++++++++");
                        NodeList Itemnd = doc.getElementsByTagName("Item");


                        for(int p=0; p<Itemnd.getLength() ; p++){


                            Node ItemNode = Itemnd.item(p);
                            if(ItemNode.getNodeType() == Node.ELEMENT_NODE){


                                Element ItemElement = (Element)ItemNode;

                        NodeList ItemCodend = ItemElement.getElementsByTagName("ItemCode");
                        Element  ItemCodeElement = (Element)ItemCodend.item(0);
                        NodeList textItemCode = ItemCodeElement.getChildNodes();
                        try{
                        System.out.println("ItemCode : " + 
                                ((Node)textItemCode.item(0)).getNodeValue().trim());
                        }
                        catch (NullPointerException err ) {
                            System.out.println ("ItemCode : empty");
                            }
                        //-------
                        NodeList Quantitynd = ItemElement.getElementsByTagName("ItemQuantity");
                        Element  QuantityElement = (Element)Quantitynd.item(0);
                        NodeList textQuantity = QuantityElement.getChildNodes();
                        try{
                        System.out.println("Quantity : " + 
                                ((Node)textQuantity.item(0)).getNodeValue().trim());
                        }
                        catch (NullPointerException err ) {
                            System.out.println ("Quantity : empty");
                            }
                        //-------

                            }
                        }

                    }

                }


            }//end of if clause


        }
        ///////////////////////////////////


    }catch (SAXParseException err) {
    System.out.println ("** Parsing error" + ", line " 
         + err.getLineNumber () + ", uri " + err.getSystemId ());
    System.out.println(" " + err.getMessage ());

    }catch (SAXException e) {
    Exception x = e.getException ();
    ((x == null) ? e : x).printStackTrace ();

    }catch (Throwable t) {
    t.printStackTrace ();
    }
    //System.exit (0);

}

}
  

请找到如下的xml

<IMessage>
<IMessageName>IM1234</IMessageName>
<IMessageDate>20140328</IMessageDate>
<IServiceOrderedType>Normal</IServiceOrderedType>
<IServiceType>AIR</IServiceType>
<Instructions>OP123456</Instructions>
<CompanyName>Test</CompanyName>
<UConsignee>
<UCompanyCode></UCompanyCode>
<UTaxNo>T1231132123</UTaxNo>
<Street1>test132132</Street1>
<Street2>Streeet1</Street2>
<PostalCode>121212</PostalCode>
<CityName>London</CityName>
<Country>UK</Country>
<TaxRegNo>121313</TaxRegNo>
<CPackage>
<CPackageType>BIG</CPackageType>
<CGrossWeight>12</CGrossWeight>
<CBarcode>54353454353</CBarcode>
<Item>
<ItemCode>IT122111</ItemCode>
<ItemQuantity>50</ItemQuantity>
</Item>
<Item>
<ItemCode>IT122851</ItemCode>
<ItemQuantity>10</ItemQuantity>
</Item>
<Item>
<ItemCode>IT122151</ItemCode>
<ItemQuantity>18</ItemQuantity>
</Item>
</CPackage>
<CPackage>
<CPackageType>MEDIUM</CPackageType>
<CGrossWeight>14</CGrossWeight>
<CBarcode>54353454354</CBarcode>
<Item>
<ItemCode>IT18581</ItemCode>
<ItemQuantity>100</ItemQuantity>
</Item>
<Item>
<ItemCode>IT98561</ItemCode>
<ItemQuantity>60</ItemQuantity>
</Item>
<Item>
<ItemCode>IT68961</ItemCode>
<ItemQuantity>12</ItemQuantity>
</Item>
</CPackage>
</UConsignee>
</IMessage>

1 个答案:

答案 0 :(得分:0)

我已经找到了应该通过嵌套NodeList方法继续迭代的答案,如下面的代码

  NodeList PackageRootNodeList = Messagend .getElementsByTagName("CPackage");

   for(int n=0; n<PackageRootNodeList .getLength() ; n++){


       Node PackageNode = PackageRootNodeList .item(s);
       Element PackageRootElement = (Element)PackageNode ;

           //-------
     

NodeList PackageBarcodeNodeList = PackageRootElement .getElementsByTagName(“CBarcode”);     Element PackageBarcodeElement =(Element)PackageBarcodeNodeList .item(0);

   NodeList textCBarcode = PackageBarcodeElement .getChildNodes();
           System.out.println("CBarcode: " + 
                  ((Node)textCBarcode.item(0)).getNodeValue().trim());

 /////
 /////   You will continue as the same methood in order to make deep iteration
 /////
           }