xml验证值null

时间:2011-11-24 05:01:04

标签: java xml junit4

我将从网络应用程序中获取一个xml,类似于下面给出的那个。

<note>
<to>Tove</to>
<from>J</from>
<heading>Reminder</heading>
<body>Some Message</body>
</note>

我能否断言标签上的值是否为null,类似于

<note>
<to></to>
<from>J</from>
<heading>Reminder</heading>
<body>Some Message</body>
</note>

我需要使用java和junit来完成它。

1 个答案:

答案 0 :(得分:2)

由于这是一个开放式问题,我将尝试为您提供一个简单的解决方案。

使用XStream将xml解析为object并将对象解析为xml。

您可以在10分钟内开始使用XStream阅读this

创建对象后,请说Note,然后您可以在junit中说出

assertNotNull(note.getTo());

以下示例代码:

我的笔记课

public class Note {
private String to = null;
private String from = null;
private String heading = null;
private String body = null;

public Note(String to, String from, String heading, String body) {
    super();
    this.to = to;
    this.from = from;
    this.heading = heading;
    this.body = body;
}

public String getTo() {
    return to;
}

public void setTo(String to) {
    this.to = to;
}

public String getFrom() {
    return from;
}

public void setFrom(String from) {
    this.from = from;
}

public String getHeading() {
    return heading;
}

public void setHeading(String heading) {
    this.heading = heading;
}

public String getBody() {
    return body;
}

public void setBody(String body) {
    this.body = body;
}

@Override
public String toString() {
    return new StringBuilder().append("To = ").append(this.getTo())
            .append(" ,From = ").append(this.getFrom())
            .append(" ,Heading = ").append(this.getHeading())
            .append(" ,Body = ").append(this.getBody()).toString();
}

}

将XML转换为Object和Object转换为XML的类

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

public class TestXStream {

public String getXMLFromObject(Note object) {
    XStream xStream = new XStream(new DomDriver());
    return xStream.toXML(object);
}

public Note getNoteFromXML(String noteXML) {
    XStream xStream = new XStream(new DomDriver());
    return (Note) xStream.fromXML(noteXML);
}

}

示例JUnit测试用例:

import static org.junit.Assert.*;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;


public class XStreamJunitTest {

@Before
public void setUp() throws Exception {
}

@After
public void tearDown() throws Exception {
}

@Test
public void test() {
    Note note = new Note("TestTo", "TestFrom", "TestHeading", "TestBody");
    TestXStream testXStream = new TestXStream();
    note = testXStream.getNoteFromXML(testXStream.getXMLFromObject(note));
    assertNotNull(note.getBody());
}

}

希望这会有所帮助并让你前进。