roymustang86
roymustang86

Reputation: 8563

How do I resolve two nodes which have the same name but under different parents?

 <PublicRecords>
      <USBankruptcies>
         <USBanktruptcy>...<USBankruptcy>
         <CourtId>...</CourtId>
         <USBanktruptcy>...<USBankruptcy>
         <CourtId>...</CourtId>
      </USBankruptcies>             
      <USTaxLiens>
         <USTaxLien>...<USTaxLien>
         <CourtId>...</CourtId>
         <USTaxLien>...<USTaxLien>
         <CourtId>...</CourtId>
      </USTaxLiens>       
      <USLegalItems>
         <USLegalItem><USLegalItem>
         <CourtId></CourtId>
          <USLegalItem><USLegalItem>
         <CourtId></CourtId>
      </USLegalItems>       
  </PubicRecords>

I am using a combination of doc and xpath objects to extract the attributes and node contents.

    NodeList bp = doc.getElementsByTagName("USBankruptcy");
    NodeList nl = doc.getElementsByTagName("CourtId");
    long itrBP;
    for (itrBP = 0; itrBP < bp.getLength(); itrBP++ )
    {

        Element docElement = (Element) bp.item(itrBP);
        Element courtElement = (Element) nl.item(itrBP);



        NodeList df = docElement.getElementsByTagName("DateFiled");
        if(df.getLength() > 0)
        {
            dateFiled = nullIfBlank(((Element)df.item(0)).getFirstChild().getTextContent());
            dateFiled = df.format(dateFiled);
        }

But, when I say get elements of tag name CourtID, it will get all the CourtIDs, not just the ones under USBankruptcy.

Is there any way to specify the parent?

I tried NodeList nl = doc.getElementsByTagName("USBankruptcies/CourtId");

It gave me a dom error on run time.

Upvotes: 0

Views: 1977

Answers (2)

ᴇʟᴇvᴀтᴇ
ᴇʟᴇvᴀтᴇ

Reputation: 12751

Rather than calling the getElementsByTagName("CourtId") method on the Document, call it on the child Element (in your case, the <USBankruptcies> element).

NodeList bankruptcyNodes = doc.getElementsByTagName("USBankruptcies");
Element bankruptcyElement = (Element) bankruptcyNodes.item(0);

NodeList bankruptcyCourtNodes = bankruptcyElement.getElementsByTagName("CourtId");
// etc...

Upvotes: 1

Phani
Phani

Reputation: 5427

Please find the code here:

DocumentBuilderFactory domFactory = DocumentBuilderFactory
            .newInstance();
    domFactory.setNamespaceAware(true);
    DocumentBuilder builder = domFactory.newDocumentBuilder();
    Document doc = builder.parse("test.xml");
    XPath xpath = XPathFactory.newInstance().newXPath();
    XPathExpression expr = xpath.compile("*//USBankruptcies/CourtId");
    Object result = expr.evaluate(doc, XPathConstants.NODESET);
    NodeList nodes = (NodeList) result;
    for (int i = 0; i < nodes.getLength(); i++) {
        System.out.println(nodes.item(i));
    }

Upvotes: 1

Related Questions