簡體   English   中英

如何解析具有相同名稱但父母不同的兩個節點?

[英]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>

我使用doc和xpath對象的組合來提取屬性和節點內容。

    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);
        }

但是,當我說獲取標簽名稱CourtID的元素時,它將獲得所有CourtID,而不僅僅是USB破產。

有沒有辦法指定父母?

我嘗試了NodeList nl = doc.getElementsByTagName(“USBankruptcies / CourtId”);

它在運行時給了我一個dom錯誤。

請在這里找到代碼:

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));
    }

而不是在Document上調用getElementsByTagName("CourtId")方法,而是在子元素(在您的情況下, <USBankruptcies>元素)上調用它。

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM