解析xml时如何检查空标签? [英] How do I check for empty tags while parsing xml?

查看:94
本文介绍了解析xml时如何检查空标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Document 对象从 xml 中提取所有标签.如果 xml 有一个空标签,我会得到一个空指针异常.我该如何防范?如何检查空标签?

I am using the Document object to extract all the tags from an xml. If the xml has an empty tag, I get a null pointer exception. How do I guard against this? How do I check for an empty tag?

<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 返回任何内容

Nodelist gives a length of 1, because there is a tag, but when I do getTextContent(), it hits the null pointer because FirstChild() doesn't return anything for tag = Name

而且,我为每个 xml 标签都做了这个.在每次提取标签之前,我可以做一个简单的检查吗?

And, I have done this for each xml tag. Is there a simple check I can do before every tag extraction?

推荐答案

我要做的第一件事就是解开你的电话.这将使您有机会准确确定哪个引用为空以及您需要对哪个引用进行空检查:

The first thing I would do would be to unchain your calls. This will give you the chance to determine exactly which reference is null and which reference you need to do a null check for:

 NodeList nm = docElement.getElementsByTagName("Name");
                if (nm.getLength() > 0) {
                    Node n = nm.item(0);
                    Node child = n.getFirstChild();
                    if(child == null) {
                        // null handling
                        name = null;
                     }
                    else {
                       name = nullIfBlank(child.getTextContent());
                    }

                 }

另外,查看 Node 上的 hasChildNodes() 方法!http:///docs.oracle.com/javase/1.4.2/docs/api/org/w3c/dom/Node.html#hasChildNodes%28%29

Also, check out the hasChildNodes() method on Node! http://docs.oracle.com/javase/1.4.2/docs/api/org/w3c/dom/Node.html#hasChildNodes%28%29

这篇关于解析xml时如何检查空标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆