简体   繁体   中英

Can't parse string with simple xml

I have pretty simple xml like this:

<EncryptedToken>11d8575638eaa52b</EncryptedToken>

Here is my java class for it:

@Root
public class EncryptedTokenDto {
@Element(name = "EncryptedToken", required = false)
private String encryptedToken;

public String getEncryptedToken() {
    return encryptedToken;
}

public void setEncryptedToken(String encryptedToken) {
    this.encryptedToken = encryptedToken;
}

}

But when I try to parse this xml encryptedToken is always null . What is wrong with my code?

UPDATE:

Here is my sample code from main :

   Serializer serializer = new Persister();

    EncryptedTokenDto encryptedTokenDto = null;
    try {
        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <EncryptedToken>11d8575638eaa52b</EncryptedToken>";
        encryptedTokenDto = serializer.read(EncryptedTokenDto.class, xml);
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (encryptedTokenDto != null) {
        System.out.println(encryptedTokenDto.getEncryptedToken());
    }

Actually it's not real code, because I receive xml from web service, but everything else works good, question is only in xml parsing.

UPDATE 2:

I've found that if I change my xml like this:

String xml = "<root> \n <EncryptedToken>11d8575638eaa52b</EncryptedToken> \n </root>";

And write class like this:

@Root
public class EncryptedTokenDto {
@Element(name = "EncryptedToken", required = false)
private String encryptedToken;

public String getEncryptedToken() {
    return this.encryptedToken;
}

public void setEncryptedToken(String encryptedToken) {
    this.encryptedToken = encryptedToken;
}
}

Everyrthing is ok.

So my question is: how is it possible to parse xml document without root relement using SimpleXml

Note: I need to use SimpleXml, I can't use any other parser.

尝试使用@Text,而不是@Element,然后可以使用

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM