我正在使用 Document 对象从 xml 中提取所有标签。如果 xml 有一个空标签,我会得到一个空指针异常。我该如何防范呢?如何检查空标签?
<USTrade>
<CreditorId>
<CustomerNumber>xxxx</CustomerNumber>
<Name></Name>
<Industry code="FY" description="Factor"/>
</CreditorId>
<DateReported format="MM/CCYY">02/2012</DateReported>
<AccountNumber>54000</AccountNumber>
<HighCreditAmount>0000299</HighCreditAmount>
<BalanceAmount>0000069</BalanceAmount>
<PastDueAmount>0000069</PastDueAmount>
<PortfolioType code="O" description="Open Account (30, 60, or 90 day account)"/>
<Status code="5" description="120 Dys or More PDue"/>
<Narratives>
<Narrative code="GS" description="Medical"/>
<Narrative code="CZ" description="Collection Account"/>
</Narratives>
</USTrade>
<USTrade>
所以,当我使用:
NodeList nm = docElement.getElementsByTagName("Name");
if (nm.getLength() > 0)
name = nullIfBlank(((Element) nm.item(0))
.getFirstChild().getTextContent());
Nodelist 给出的长度为 1,因为有一个标签,但是当我执行 getTextContent() 时,它会命中空指针,因为 FirstChild() 没有为 tag = Name 返回任何内容
而且,我已经为每个 xml 标签做了这个。在每次提取标签之前我可以做一个简单的检查吗?