如果元素值为空,则使用java进行stax解析,然后将解析元素分配给upper元素

时间:2016-11-06 01:16:58

标签: java xml stax

我正在使用stax解析器解析大的xml输入数据。

我的输入xml部分将如下所示

<User>
<LoginName>abcd</LoginName>
<FirstName>abcd</FirstName>
<LastName>kkk</LastName>
<CompanyName>infosys</CompanyName>
<EmailAddress>mmm@gmail.com</EmailAddress>
<CorporateEmailAddress></CorporateEmailAddress>
</User>

我的stax代码如下

private static Message parseMessage(XMLStreamReader xr)
            throws XMLStreamException {
        String userName = null;
        String content = null;
        String email = null;
        String comp = null;

        while (xr.hasNext()) {
            int event = xr.next();
            switch (event) {
                case XMLStreamConstants.START_ELEMENT: {
                    String elName = xr.getLocalName();
                    if (LOGIN_NAME.equals(elName)) {
                        userName = xr.getElementText();
                    } else if (CONTENT.equals(elName)) {
                        content = StringUtils.trimToEmpty(xr.getElementText());
                        content = content.replace("\n"," "); 
                    } else if (CORP_EMAIL_ADDRESS.equals(elName)) {
                        email = xr.getElementText();
                        /*if(email.equals(""))
                            email ="unknown";*/

                        conv.emails.add(email);
                    } 
                    else if (COMPANY_NAME.equals(elName)) {
                        comp = xr.getElementText();
                        conv.comps.add(comp);
                        //System.out.println(comp);
                    } 
                    break;
                }
                case XMLStreamConstants.END_ELEMENT: {
                    String elName = xr.getLocalName();
                    if (MESSAGE.equals(elName)) {

                        return new Message(userName, content,email);
                    }
                    break;
                }
                case XMLStreamConstants.END_DOCUMENT:
                    throw new XMLStreamException("xml not well-formed: <"
                        + MESSAGE + "> tag not closed");
            }


        }

这里是代码,如果xr.getElementText(email)为null,因为没有任何值。所以在这种情况下我想使用标签值

那么如何再次将xr.elementText分配给loginvalue?仅当cor-email为空时

请帮忙

0 个答案:

没有答案